Flutter:默认标签栏控制器在滑动后不保持状态

San*_* GS 3 android ios dart flutter

我正在用 flutter 编写一个应用程序,它有 4 个选项卡式视图,有点像股票的 android 手机应用程序或时钟应用程序。其中一个视图散列一个浮动操作按钮,按下该按钮时会在列表中添加一些文本。但是,当我滚动到其他视图之一并返回时,所有文本都消失了。有没有办法来解决这个问题?

这是我的代码:

import 'package:flutter/material.dart';
import 'Screens/Dashboard.dart';
import 'Screens/CreateQuestionnaire.dart';
import 'Screens/AccountScreen.dart';

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

class MyApp extends StatefulWidget {
  @override
 createState() => new MyAppState();
}

class MyAppState extends State<MyApp> {
  final primaryColour = const Color(0xFF5CA1CA);
  final secondaryColour = const Color(0xFFC36B42);
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new DefaultTabController(
        length: 4,
        child: new Scaffold(
          appBar: new AppBar(
            actions: <Widget>[
              new IconButton(icon: new Icon(Icons.account_circle),
              onPressed: (){
                Navigator.push(context, new MaterialPageRoute(builder: (context) => new AccountScreen()));
              }),
            ],
            bottom: new TabBar(
              tabs: <Widget>[
                new Tab(icon: new Icon(Icons.home)),
                new Tab(icon: new Icon(Icons.contacts)),
                new Tab(icon: new Icon(Icons.description)),
                new Tab(icon: new Icon(Icons.settings))
              ],
            ),
            title: new Text("NLPro Questionnaire"),
          ),
          body: new TabBarView(
            children: <Widget>[
              new Dashboard(),
              new CreateQuestionnaire(),
              new Text("Surveys"),
              new Text("Settings")
            ],
          ),
        ),
      ),
      theme:new ThemeData(
        primaryColor: primaryColour,
        accentColor: secondaryColour,
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

sud*_*esh 9

您需要在有状态小部件上使用AutomaticKeepAliveClientMixin并实现名为wantKeepAlive 的覆盖方法

class MyApp extends StatefulWidget {
@override
createState() => new MyAppState();
}
Run Code Online (Sandbox Code Playgroud)

将 AutomaticKeepAliveClientMixin 与您的类扩展 state 和 ov 一起使用

class MyAppState extends State<MyApp> with AutomaticKeepAliveClientMixin<MyApp>{

//your existing code.....

@override
bool get wantKeepAlive => true;   //by default it will be null, change it to true.

//your existing code......

}
Run Code Online (Sandbox Code Playgroud)

将 wantKeepAlive 设置为 true 时,initState 方法将仅在创建时运行一次。


Bos*_*rot 2

Flutter 中在 Stateful widget 内创建的变量会随着状态的变化而更新。当您转到另一个视图然后返回时,状态会发生变化。所以你能做的就是定义两个变量。一种是临时的,仅用于布局,另一种是可以保存较长时间的。伪代码:

var globalVar;
Stateful Widget...
var _temp;
setState({_temp=yourData; globalVar=yourData})
doSomethingWithYourText(_temp != null ? _temp : globalVar)
Run Code Online (Sandbox Code Playgroud)

当您使用_tempvar 进行所有布局更新时。在状态重置(您更改为另一个视图)之前,globalVar 的更改不会被注意到。

所以它的作用是将你的数据保存在两个变量中,并检查状态之前是否被使用过。如果没有,它使用之前保存的 var。