Flutter:默认选项卡控制器在滑动后不会保持状态

5
我正在使用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,
      ),
    );
  }
}

在此输入图片描述

4个回答

12

您需要在有状态小部件上使用AutomaticKeepAliveClientMixin,并实现名为wantKeepAlive的重写方法。

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

使用AutomaticKeepAliveClientMixin来扩展你的State类并进行覆盖

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......

}

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


1
你应该使用上述的AutomaticKeepAliveClientMixin创建一个小部件,然后在TabBarView中使用它。这样可以解决问题。 - praveenb

2
Flutter中在Stateful widget内创建的变量会随着状态的改变而更新。当您切换到另一个视图然后返回时,状态会发生改变。 因此,您可以定义两个变量。一个是临时变量,只用于布局,另一个则长期保存在存储器中。伪代码如下:
var globalVar;
Stateful Widget...
var _temp;
setState({_temp=yourData; globalVar=yourData})
doSomethingWithYourText(_temp != null ? _temp : globalVar)

当您使用_temp变量进行所有布局更新时,全局变量的更改在状态重置(切换到另一个视图)之前将不会被注意到。
因此,这样做可以将数据保存在两个变量中,并检查是否先前使用过该状态。如果没有,则使用先前保存的变量。

2

1
虽然这个链接可能回答了问题,但最好在此处包含答案的基本部分并提供参考链接。如果链接页面更改,仅链接的答案可能会失效。-【来自审查】 - MJM
是的,你说得对。我已经更新了我的答案,并提供了解决方案的概述。 - Javid Noutash
我也尝试了这种方法,但它没有起作用。我是否已经创建了某种类型的数据使其能够工作? - Santi GS

1
class _RepoInfoState extends State<RepoInfo> with AutomaticKeepAliveClientMixin {

  @override
  bool get wantKeepAlive => true; // Note here

  @override
  Widget build(BuildContext context) {
    super.build(context); // Note here

    return Text('嘿');
  }

}

3
请问您能否在您的回答中添加一些解释说明,以帮助其他人理解吗? - Our Man in Bananas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接