dart Flutter如何创建列表视图自动滚动?

lrpiutwd  于 2023-04-27  发布在  Flutter
关注(0)|答案(4)|浏览(134)

我试图创建一个ListView,它可以自动滚动到最新的数据点。我尝试通过创建一个使用.jumpTo方法的_scrollToBottom函数来实现这一点。
但是我在应用程序中得到一个空白屏幕,在调试控制台中得到'child.parentData != null': is not true.
有什么建议可以实现自动滚动吗?
下面是我当前代码的相关部分:

ScrollController _scrollController = ScrollController();

_scrollToBottom(){  _scrollController.jumpTo(_scrollController.position.maxScrollExtent);
}

@override
  Widget build(BuildContext context) {
    return StreamBuilder(
      stream: DataShareWidget.of(context).stream,
      builder: (BuildContext context, AsyncSnapshot snapshot){
        if(snapshot.hasError){ return Text(snapshot.error);}
        if(snapshot.hasData){
          _dataFormat(snapshot.data);
          return ListView.builder(
            itemCount: _listViewData.length,
            controller: _scrollController,
            reverse: true,
            shrinkWrap: true,
            itemBuilder: (context, index) {
              _scrollToBottom();
              return ListTile(
                title: AutoSizeText(_listViewData[index], maxLines: 2),
                dense: true,
              );
            },
          );
        }
      }
    );
  }
gajydyqb

gajydyqb1#

你需要做的是在列表构建完成后调用_scrollToBottom()方法。
修改是你的代码(没有StreamBuilder):

ScrollController _scrollController = ScrollController();
    
      _scrollToBottom() {
        _scrollController.jumpTo(_scrollController.position.maxScrollExtent);
      }
      
      @override
      void initState() {
        super.initState();
      }
    
      @override
      Widget build(BuildContext context) {
        WidgetsBinding.instance.addPostFrameCallback((_) => _scrollToBottom()); 
        return Scaffold(
          body: ListView.builder(
            itemCount: 50,
           // itemCount: _listViewData.length,
            controller: _scrollController,
            reverse: true,
            shrinkWrap: true,
            itemBuilder: (context, index) {
              return ListTile(
                title: Text('Yo Dummy Text $index'),
                // title: AutoSizeText(_listViewData[index], maxLines: 2),
                dense: true,
              );
            },
          ),
        );
      }
44u64gxh

44u64gxh2#

你需要这样做,并完美地工作。。。

ScrollController _scrollController = ScrollController();
  
  @override
  Widget build(BuildContext context) {
    _scrollController.animateTo(_scrollController.position.maxScrollExtent, duration: Duration(milliseconds: 200), curve: Curves.easeOut);
    return StreamBuilder(
      stream: stream = Firestore.instance
          .collection('your collaction')
          .document('your document')
          .snapshots(),
      builder: (context, snapshot) {
        return snapshot.hasData
            ? ListView.builder(
                controller: _scrollController,
                shrinkWrap: true,
                itemCount: snapshot.data.documents.length,
                itemBuilder: (context, index) =>
                    msgTile(snapshot.data.documents[index], user1),
              )
            : Text('Loading...');
      },
    );
  }
roejwanj

roejwanj3#

问题出在你的StreamBuilder代码中。如果快照还没有准备好,你需要返回一些东西。试试下面的代码:

ScrollController _scrollController = ScrollController();

_scrollToBottom(){  _scrollController.jumpTo(_scrollController.position.maxScrollExtent);
}

@override
  Widget build(BuildContext context) {
    return StreamBuilder(
      stream: DataShareWidget.of(context).stream,
      builder: (BuildContext context, AsyncSnapshot snapshot){
        if(snapshot.hasError){ return Text(snapshot.error);}
        if(snapshot.hasData){
          _dataFormat(snapshot.data);
          return ListView.builder(
            itemCount: _listViewData.length,
            controller: _scrollController,
            reverse: true,
            shrinkWrap: true,
            itemBuilder: (context, index) {
              _scrollToBottom();
              return ListTile(
                title: AutoSizeText(_listViewData[index], maxLines: 2),
                dense: true,
              );
            },
          );
        }
        //Something waiting the snapshot
        return CircularProgressIndicator();
      }
    );
  }
yhqotfr8

yhqotfr84#

在flutter 3.7+中,可以使用以下代码轻松完成。

class _HomePageState extends State<HomePage> {
  ScrollController scrollController = ScrollController(); // 👈 Define scrollController 
  List<String> assets = [...] // String of images to be displayed in listview

  @override
  void initState() { // 👈 create animation in initState
    Future.delayed(const Duration(seconds: 1), () {
      scrollController.animateTo(scrollController.position.maxScrollExtent,
          duration: Duration(seconds: asset.length * 10), curve: Curves.linear);
    });

   //👉 If you want infinite scrolling use the following code 
    scrollController.addListener(() {
      if (scrollController.position.pixels ==
          scrollController.position.maxScrollExtent) {
        // Scroll has reached the end, reset the position to the beginning.
        scrollController.jumpTo(scrollController.position.minScrollExtent);
      }
    });
    super.initState();
  }

  @override
  void dispose() {
    scrollController.dispose();
    super.dispose();
  }

@override
  Widget build(BuildContext context) {
    var size = MediaQuery.of(context).size;
    return Scaffold(
      body: SizedBox(
        width: size.width,
        height: size.height,
        child: ListView.builder(
                  controller: scrollController, // 👈 assign scrollController here
                  ....
                  // display your images here
               ),
             ),
       );
  }

相关问题