在flutter应用程序中导航到不同屏幕时,如何使列表持久化?

时间:2019-11-29 12:25:09

标签: flutter navigation persistence bottomnavigationview

在我的flutter应用程序中,存在底部导航栏,并且有两个底部导航栏项。我在两个屏幕上都使用列表视图。当我在某个屏幕上滚动后从一个屏幕导航到另一个屏幕时。我回到列表的顶部,而不是离开的最后一个位置。如何在两个屏幕上都保持住状态?

3 个答案:

答案 0 :(得分:1)

您可以将keepScrollOffset设置为true。 https://api.flutter.dev/flutter/widgets/ScrollController-class.html

答案 1 :(得分:0)

您可以使用PageStorageKey

@override
Widget build(BuildContext context) {
    return ListView.builder(
        key: new PageStorageKey('key_name'),
        itemBuilder: ...
    );
}

答案 2 :(得分:0)

您可以使用PageStoragePageBucket保存ListView的滚动偏移量。

工作示例为https://codepen.io/ntaoo/pen/LYpyrZJ

关键部分如下,

final bucket = PageStorageBucket(); _widgetOptions = <Widget>[ PageStorage( bucket: bucket, child: ListView( key: PageStorageKey<String>('0'), children: <Widget>[ Text( 'Index 0: Home Start\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n to... \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nEnd', style: optionStyle, ), ], ), ), PageStorage( bucket: bucket, child: ListView( key: PageStorageKey<String>('1'), children: <Widget>[ Text( 'Index 1: Business Start\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n to... \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nEnd', style: optionStyle, ), ], ), ), PageStorage( bucket: bucket, child: ListView( key: PageStorageKey<String>('2'), children: <Widget>[ Text( 'Index 2: School Start\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n to... \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nEnd', style: optionStyle, ), ], ), ), ];

ScrollController测试代码是keepScrollOffset'的完美用法示例。

https://github.com/flutter/flutter/blob/master/packages/flutter/test/widgets/scroll_controller_test.dart#L313