【问题标题】:Flutter: How to restore ListView position?Flutter:如何恢复 ListView 位置?
【发布时间】:2018-01-30 10:42:28
【问题描述】:

当路由主控ListView 及其详细信息ItemViewNavigator 时,ListView 的滚动位置在返回堆栈上丢失。

如何恢复ListView的滚动位置?

重用 ListView 小部件也丢失了位置 - 在颤振示例中也没有看到重用小部件。

Rainer 要求的示例代码,

 Widget build(BuildContext context) {
return new MaterialApp(

  routes: <String, WidgetBuilder>{
    '/': (BuildContext context) => new MyListView(),
  },
  onGenerateRoute: (RouteSettings s) {
    final List<String> paths = name.split('/');
    ...
    return new new ItemView(paths[1])
  }
}

MyListView,当ItemRow.onTab =&gt; Navigator.pushNamed(c, '/item/1')

ItemView后退按钮调用Navigator.pushNamed('/');

两个 Widget 都是有状态的

【问题讨论】:

  • 我无法重现该问题。我的 ListView 保持状态。您的 ListView 是包裹在 Stateful 还是 StatelessWidget 中?你能分享一些代码吗?
  • 可能是Navigator.pop() 恢复以前的小部件状态。两个小部件都是有状态的。
  • 我明白了。它应该saved scroll position。我一定是错过了什么。

标签: flutter


【解决方案1】:

这应该可行。这是一些示例代码。

import 'package:flutter/material.dart';

void main() {
  runApp(new MaterialApp(
    home: new MyHomePage(),
  ));
}

class MyHomePage extends StatelessWidget {
  Widget build(BuildContext context) {
    return new Scaffold(
      body: new ListView(
          children: new List.generate(100, (int index) {
            return new ListTile(
              title: new Text('Item $index'),
              onTap: () {
                Navigator.push(
                  context,
                  new MaterialPageRoute(
                    builder: (BuildContext context) {
                      return new Scaffold(
                        body: new Center(
                          child: new RaisedButton(
                            child: new Text('Pop!'),
                            onPressed: () => Navigator.pop(context),
                          ),
                        ),
                      );
                    },
                  ),
                );
              },
            );
          },
        ),
      ),
    );
  }
}

确保您使用 Navigator.pop() 而不是 Navigator.pushNamed('/'); 返回。如果不起作用,请发布更多代码或file an issue

【讨论】:

  • 为什么Navigator.pushNamed('/'); 不起作用?如果new List.generate(100, (int index) {key: const ValueKey('100');}ListView 应该恢复偏移量。
  • Push 将新的空路由添加到导航器堆栈。 Pop 恢复以前的路线
  • 只是想补充一点,要恢复ListView的位置,必须重用ListView,所以在过渡期间不能改变ListView的Widget Key及其父键。
猜你喜欢
  • 2011-11-02
  • 1970-01-01
  • 2020-01-14
  • 2019-06-01
  • 1970-01-01
  • 2011-03-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多