3

我有一个带有 ListView 的小部件,我经常使用Navigator.push(). 我正在尝试使用键(PageStorageKey/UniqueKey/GlobalKey)保留滚动,但没有任何运气。

https://gist.github.com/JellyO1/dd8b50a5bcf2e5c10d7a4047427943c8

4

1 回答 1

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 设备中的后退按钮,以保存偏移量。

于 2019-01-21T11:50:58.500 回答