flutter - Flutter:如何在屏幕之间保持 ListView 滚动位置
问题描述
我有一个 Flutter 应用程序,它有BottomNavigationBar
两个选项卡:主页和个人资料。个人资料有一个ListView
包含基本个人资料信息和一个GridView
帖子。在两个选项卡之间切换时,我希望保持滚动位置ListView
。我正在PageStorageKey
这样做(正如其他 StackOverflow 答案所指出的那样:例如这里),但它没有给出这个 gif 所示的预期结果:
有两点不对:
- 当返回到 Profile 选项卡时,位置会恢复,但它是通过滚动到该位置来恢复的;
- 再次离开“个人资料”选项卡(无需进一步滚动)
ListView
时,再次访问“个人资料”选项卡时,它会导致从顶部开始。
我该如何解决这些问题?
以下是相关代码:
// Tab navigation
class NavigatorScreen extends StatefulWidget {
@override
_NavigatorScreenState createState() => _NavigatorScreenState();
}
class _NavigatorScreenState extends State<NavigatorScreen> {
var _selectedIndex = 0;
final _bucket = PageStorageBucket();
final _screens = List<Widget>.unmodifiable([
HomeScreen(key: PageStorageKey('home')),
ProfileScreen(key: PageStorageKey('profile')),
]);
void _onItemTapped(int index) {
setState(() => _selectedIndex = index);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: PageStorage(
child: _screens[_selectedIndex],
bucket: _bucket,
),
bottomNavigationBar: BottomNavigationBar(
items: const [
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Home',
),
BottomNavigationBarItem(
icon: Icon(Icons.person),
label: 'Profile',
),
],
currentIndex: _selectedIndex,
onTap: _onItemTapped,
),
);
}
}
// Profile tab content
class ProfileScreen extends StatelessWidget {
const ProfileScreen({required Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Profile'),
),
body: ListView(
key: PageStorageKey('profileList'),
children: [
Padding(
padding: EdgeInsets.all(16.0),
child: Column(
children: [
UserDetails(),
PostStats(),
PostGrid(), // GridView.builder()
],
),
),
],
),
);
}
}