我有一个带有ListView的小部件,我经常使用Navigator.push()
进行导航。我正在尝试使用键(PageStorageKey / UniqueKey / GlobalKey)来保持滚动,而没有任何运气。
https://gist.github.com/JellyO1/dd8b50a5bcf2e5c10d7a4047427943c8
答案 0 :(得分:0)
我相信您在弹出堆栈顶部的屏幕时正在尝试保存滚动状态。您可以通过几种方式实现此目的,但是可以通过提供初始偏移量并使用自定义ScrollController
将其保存回上下文弹出窗口中来完成。这是您编辑的示例。
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
double scrollOffset = 0.0;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Container(),
floatingActionButton: FloatingActionButton(
onPressed: () async {
scrollOffset = await Navigator.of(context).push(MaterialPageRoute(
builder: (context) => Scrollable(
scrollOffset: scrollOffset,
)));
},
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
class Scrollable extends StatefulWidget {
final double scrollOffset;
@override
State createState() {
return _ScrollableState();
}
Scrollable({this.scrollOffset, Key key}) : super(key: key);
}
class _ScrollableState extends State<Scrollable> {
ScrollController myScrollController;
List<Widget> list = List.generate(500, (index) => Text('$index'));
@override
void initState() {
super.initState();
myScrollController = ScrollController(initialScrollOffset: widget.scrollOffset);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.arrow_back),
onPressed: () => Navigator.of(context).pop(myScrollController.offset),
),
),
body: ListView(
controller: myScrollController,
children: list,
),
);
}
}
但是,我也想知道是否有可能通过使用PageStorageKey
使它变得更加简单。
注意:如果需要,请不要忘记使用WillPopScope
小部件覆盖Android设备中的后退按钮。