【问题标题】:Scroll a future ListView滚动未来的 ListView
【发布时间】:2019-10-25 01:20:49
【问题描述】:

我正在创建一个包含项目列表的页面。我想在列表呈现后滚动到页面底部。问题是我正在使用 FutureBuilder 来获取列表。如果我使用WidgetsBinding.addPostFrameCallback,这似乎在build() 方法完成之前被调用(可能是因为它仍在获取数据的过程中)。

有没有办法判断一个 Future 已经完成,列表已经渲染,然后才触发滚动到底部?

@override
void initState() {

  WidgetsBinding.instance.addPostFrameCallback((_) => _postInit());

  super.initState();
}

Future<void> _postInit() async {
 _scrollController.jumpTo(_scrollController.position.maxScrollExtent);
}

@override
Widget build(BuildContext context) {
  return Scaffold(
    body: FutureBuilder(
      future: _getList(),
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        switch(snapshot.connectionState) {
          case ConnectionState.none:
          case ConnectionState.waiting:
            return Center(child: SizedBox(height: 100, width: 100, child: new CircularProgressIndicator()));
            break;
          default:
            if(snapshot.hasError) {
              return Container();
            } else {
              return _buildListView(snapshot.data);
            }
          }
      }

    )
  );
}

Widget _buildListView(list) {
  return Column(
    children: <Widget>[
      Expanded(
        child: ListView(
          controller: _scrollController,
          shrinkWrap: true,
          children: list,
        ),
      ),
    ],
  );
}

【问题讨论】:

  • 当然,添加一个简单的代码来重现问题,以便我们帮助您编写代码

标签: flutter dart


【解决方案1】:

尝试从您的 initState 方法中删除 WidgetsBinding.instance.addPostFrameCallback((_) =&gt; _postInit());

之后,在您的_postInit() 方法中添加一个delayed 函数,并在收到数据时调用它以显示您的列表,如下所示:

Future<void> _postInit() async {
   await Future.delayed(Duration(milliseconds: 100));
 _scrollController.jumpTo(_scrollController.position.maxScrollExtent);
}


@override
Widget build(BuildContext context) {
  return Scaffold(
    body: FutureBuilder(
      future: _getList(),
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        switch(snapshot.connectionState) {
          case ConnectionState.none:
          case ConnectionState.waiting:
            return Center(child: SizedBox(height: 100, width: 100, child: new CircularProgressIndicator()));
            break;
          default:
            if(snapshot.hasError) {
              return Container();
            } else {
              _postInit();
              return _buildListView(snapshot.data);
            }
          }
      }

    )
  );
}

【讨论】:

    猜你喜欢
    • 2019-04-07
    • 1970-01-01
    • 2011-09-20
    • 1970-01-01
    • 1970-01-01
    • 2013-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多