程序问答   发布时间:2022-06-01  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了如何在 Flutter 列表视图流构建器中停止自动滚动?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决如何在 Flutter 列表视图流构建器中停止自动滚动??

开发过程中遇到如何在 Flutter 列表视图流构建器中停止自动滚动?的问题如何解决?下面主要结合日常开发的经验,给出你关于如何在 Flutter 列表视图流构建器中停止自动滚动?的解决方法建议,希望对你解决如何在 Flutter 列表视图流构建器中停止自动滚动?有所启发或帮助;

当消息流在列表视图中不断流动时,继续向下滚动会在阅读特定消息时产生干扰。有没有办法在阅读一些已经可用的流消息时避免自动滚动? 这是我试图在列表视图中显示流消息的代码

 List<Comment> comments = <Comment>[];
  StreamSubscription<Comment>? sub;
  Future<voID> redditmain() async {
    SharedPreferences preferences = await SharedPreferences.geTinstance();

 
    Reddit reddit = await Reddit.createScripTinstance(
      clIEntID: cID,clIEntSecret: cSecret,userAgent: uAgent,username: uname,password: upassword,// Fake
    );
   
    sub = reddit.subreddit('cricket').stream.comments().Listen((comment) {
      if (comment != null) {
   
        setState(() {
          comments.insert(0,comment);
        });
       
      }
    }) as StreamSubscription<Comment>?;
  }

  @overrIDe
  Future<voID> dIDChangeDependencIEs() async {
    super.dIDChangeDependencIEs();
   
    redditmain();
  }

  @overrIDe
  Widget build(BuildContext context) {
    return Scaffold(
      
        body:Center(
                child: Container(
                  child: Scrollbar(
                    child: ListVIEw.builder(
                      scrollDirection: Axis.vertical,itemCount: comments.length,itemBuilder: (context,indeX) {
                        if (comments.isnotEmpty) {
                          final Comment comment = comments[index];
                          return Card(
                            elevation: 3,semanticContainer: true,clipBehavior: Clip.antiAliasWithSaveLayer,color: getMycolor(comment
                                    .data!["author_flair_richtext"].isnotEmpty
                                ? comment.data!['author_flair_richtext'][0]['a']
                                : ''),child: ListTile(
                              onTap: () {
                                _launchURL(comment.permalink);
                              },Trailing: Text(
                                comment.author,style: TextStyle(color: text_color),),title: Text(
                                comment.body ?? '',subtitle: Text(comment.data?['link_title'] ?? '',style: TextStyle(color: text_color)),leading: Image.network(comment
                                      .data!["author_flair_richtext"].isnotEmpty
                                  ? comment.data!['author_flair_richtext'][0]
                                          ['u'] ??
                                      "https://png.pngtree.com/png-clipart/20190927/ourmID/pngtree-cricket-stuR_718_11845@ps-and-ball-png-image_1733735.jpg"
                                  : "https://png.pngtree.com/png-clipart/20190927/ourmID/pngtree-cricket-stuR_718_11845@ps-and-ball-png-image_1733735.jpg"),// Text(comment.data?['author_flair_CSS_class'] ?? ''),);
                        } else
                          return theme(
                            data: theme.of(context)
                                .copyWith(accentcolor: colors.red),child: new CircularProgressInDicator(),);
                      },));
  }

这使得流以更高的速率持续流动,因此当我向下滚动以阅读特定消息时,它会随着新的流消息进入而不断移动。 我想在不从传入流中向下滚动页面的情况下阅读消息有没有办法实现这一点?对此的任何建议都会非常有帮助,期待您的解决方案。

编辑 我尝试了@downgrade 给出的解决方案并更新了我的代码如下。最初,它加载消息流并显示滚动到屏幕底部。当我滚动到顶部时,所有列表视图都变成了一个圆形指示器,如图

如何在 Flutter 列表视图流构建器中停止自动滚动?

List<Comment> comments = <Comment>[];
  StreamSubscription<Comment>? sub;
  late StreamQueue<Comment?> commentQueue;
  static const int commentlimit = 100;
  Future<voID> redditmain() async {



    Reddit reddit = await Reddit.createScripTinstance(
      clIEntID: cID,// Fake
    );
    setState(() {
      commentQueue = StreamQueue<Comment?>(
          reddit.subreddit('cricket').stream.comments(limit: commentlimit));
    });


  }

  @overrIDe
  Future<voID> dIDChangeDependencIEs() async {
    super.dIDChangeDependencIEs();
    // getEmail();
    redditmain();
  }

  @overrIDe
  Widget build(BuildContext context) {
    return Scaffold(
     
      body: cID == null
          ? Container(
              color: colors.transparent,child: Center(
                child: CircularProgressInDicator(
                  valuecolor:
                      AlwaysstoppedAnimation<color>(colors.deepPurpleAccent),)
          : Center(
              child: Container(
                child: Scrollbar(
                  child: ListVIEw.builder(
                    reverse: true,scrollDirection: Axis.vertical,itemCount: commentlimit,indeX) => FutureBuilder<Comment?>(
                      future: commentQueue.next,builder:
                          (BuildContext ctx,AsyncSnapshot<Comment?> snap) {
                        final Comment? comment = snap.data;
                        if (comment == null) {
                          return Card(
                            elevation: 3,child: ListTile(
                              title: CircularProgressInDicator(),);
                        }
                        return Card(
                          elevation: 3,// color: (index % 2 == 0) ? colors.yellow : colors.white,// child:Image.network('https://placeimg.com/640/480/any',fit:BoxFit.fill),color: getMycolor(comment!
                                  .data!["author_flair_richtext"].isnotEmpty
                              ? comment!.data!['author_flair_richtext'][0]['a']
                              : ''),child: ListTile(
                            onTap: () {
                              _launchURL(comment.permalink);
                            },Trailing: Text(
                              comment.author,title: Text(
                              comment.body ?? '',leading: Image.network(comment
                                    .data!["author_flair_richtext"].isnotEmpty
                                ? comment.data!['author_flair_richtext'][0]
                                        ['u'] ??
                                    "https://png.pngtree.com/png-clipart/20190927/ourmID/pngtree-cricket-stuR_718_11845@ps-and-ball-png-image_1733735.jpg"
                                : "https://png.pngtree.com/png-clipart/20190927/ourmID/pngtree-cricket-stuR_718_11845@ps-and-ball-png-image_1733735.jpg"),);
  }

解决方法

编辑:我误解了这个问题。看起来 OP 想要一个反向列表,当到达列表边缘时,它会获取队列中的下一条评论。以下是使用 async 包的一种可能方法:

late StreamQueue<Comment?> commentQueue;
static const int commentLimit = 100;

Future<void> redditmain() async {
  Reddit reddit = await Reddit.createScripTinstance(
    clientId: cId,clientSecret: cSecret,userAgent: uAgent,username: uname,password: upassword,// Fake
  );

  commentQueue = StreamQueue<Comment?>(
      reddit.subreddit('cricket').stream.comments(limit: commentLimit));
}

@override
Future<void> didChangeDependencies() async {
  super.didChangeDependencies();

  redditmain();
}

@override
Widget build(BuildContext context) {
  return Scaffold(
      body: Center(
    child: Container(
      child: Scrollbar(
        child: ListView.builder(
          reverse: true,scrollDirection: Axis.vertical,itemCount: commentLimit,itemBuilder: (context,indeX) => FutureBuilder<Comment?>(
              future: commentQueue.next,builder: (BuildContext ctx,AsyncSnapshot<Comment?> snap) {
                final Comment? comment = snap.data;
                if (comment == null) {
                  return ListTile(
                    title: CircularProgressInDicator(),);
                }
                return ListTile(
                  title: Text(comment.body ?? ''),);
              }),),));
}

这利用 async 包的 StreamQueue 通过 next() 方法将流从推送行为转换为拉取行为。然后我们将 next() 传递给 ListView.builder 中的未来构建器。

此外,我们不是反向构建列表,然后从中构建列表视图,而是使用 ListView 上的反向可选标志告诉它使用反向滚动控制器。

请注意,一些改进方法可能包括检查 StreamQueue 的 hasNext() 方法,以防止在没有评论时尝试获取另一条评论。目前,如果您用尽评论列表或超过 100 条评论,您最终可能会看到一个无限显示循环进度指示器的列表磁贴。

加载状态的 UI 也可以改进。这个例子应该只是作为在需要时拉取流事件而不是等待它们推送的概念证明。

原答案

为了延迟流,您可以使用 pause() 方法。对您的问题最直接的回答是像这样修改您的 .listen 回调:

if (comment != null) {
  setState(() {
    comments.insert(0,comment);
  });
  
  // Delay next item for one second
  sub.pause(Future.delayed(Duration(seconds: 1))); 
}

但是,您可能希望立即加载一定数量的评论,然后在显示第一批评论后延迟:

List<Comment> comments = <Comment>[];
StreamSubscription<Comment>? sub;
var firstBatch = 10; // How many comments should we load first?

Future<void> redditmain() async {
  Reddit reddit = await Reddit.createScripTinstance(
    clientId: cId,// Fake
  );

  sub = reddit.subreddit('cricket').stream.comments().listen((comment) {
    if (comment != null) {
      setState(() {
        comments.insert(0,comment);
      });
      if (firstBatch == 0) {
        // First load is done,delay all remaining
        sub.pause(Future.delayed(Duration(seconds: 1)));
      } else {
        // First load is pending,decrement counter
        firstBatch--;
      }
    }
  }) as StreamSubscription<Comment>?;
}

这将在屏幕启动并且流可用后立即加载 10 条评论,之后的所有评论将每秒加载一条。

,

仅使用 ListView 即可,添加 ListView.builder 将使其可滚动,因为 ListView.builder 用于动态列表。

大佬总结

以上是大佬教程为你收集整理的如何在 Flutter 列表视图流构建器中停止自动滚动?全部内容,希望文章能够帮你解决如何在 Flutter 列表视图流构建器中停止自动滚动?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。