flutter - 在 Flutter PageView 中切换页面时丢失小部件状态

我在由 PageController 管理的 PageView 中有一系列有状态的小部件。我正在使用 pageController.jumpToPage(index) 来切换页面。切换页面时,小部件中的所有状态似乎都丢失了,就好像它是从头开始重新创建的。我曾尝试在 PageController 中使用 keepPage: true 但这似乎没有任何效果。这是 PageView 的预期行为还是我做错了什么?任何建议表示赞赏,谢谢!

最佳答案

与 AutomaticKeepAliveClientMixin 一起使用到您的子页面。

然后@override bool get wantKeepAlive => true; 这是一个示例

import 'package:flutter/material.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 4,
      child: new Scaffold(
        appBar: new AppBar(
          bottom: new TabBar(
            tabs: [
              new Tab(icon: new Icon(Icons.directions_car)),
              new Tab(icon: new Icon(Icons.directions_transit)),
              new Tab(icon: new Icon(Icons.directions_bike)),
              new Tab(
                icon: new Icon(Icons.airplanemode_active),
              )
            ],
          ),
        ),
        body: new TabBarView(children: [
          new OnePage(color: Colors.black,),
          new OnePage(color: Colors.green,),
          new OnePage(color: Colors.red,),
          new OnePage(color: Colors.blue,),
        ]),
      ),
    );
  }
}

class OnePage extends StatefulWidget {
  final Color color;

  const OnePage({Key key, this.color}) : super(key: key);

  @override
  _OnePageState createState() => new _OnePageState();
}

class _OnePageState extends State<OnePage> with AutomaticKeepAliveClientMixin<OnePage> {
  @override
  Widget build(BuildContext context) {
    super.build(context);
    return new SizedBox.expand(
      child: new ListView.builder(
        itemCount: 100,
        itemBuilder: (context, index) {
          return new Padding(
            padding: const EdgeInsets.all(10.0),
            child: new Text(
              '$index',
              style: new TextStyle(color: widget.color),
            ),
          );
        },
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}

https://stackoverflow.com/questions/45944777/

相关文章:

flutter - 当 Flutter TextField 中的键盘可见时,键盘顶部有很多空白区域

string - flutter/Dart : Convert HEX color string t

flutter - 保留选项卡 View 页面之间的状态

android - 为什么我的 Flutter 应用的 ListView 滚动不如 Flutter

android - 在 Scroll Flutter 上隐藏 Appbar?

dart - Flutter - 翻牌效果

flutter - 小部件测试失败,未找到任何 MediaQuery 小部件

google-maps - Flutter中的谷歌地图没有响应触摸事件

android - Flutter 中的 HTTP 请求

dart - 每 x 秒 flutter 一次运行功能