[英]Flutter: Default Tab Bar Controller does not maintain state after swipe
我正在编写具有4个选项卡式视图的Flutter应用程序,有点像普通的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,
),
);
}
}
您需要在有状态窗口小部件上使用AutomaticKeepAliveClientMixin ,并实现名为wantKeepAlive的替代方法
class MyApp extends StatefulWidget {
@override
createState() => new MyAppState();
}
在类的扩展状态和ov中使用AutomaticKeepAliveClientMixin
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方法在创建时将仅运行一次。
在状态更改内,在Flutter中创建的变量会在状态更改时进行更新。 当您转到另一个视图然后返回时,状态会更改。 因此,您可以做的是定义两个变量。 一种临时布局,仅用于布局,一种用于存放更长的时间。 伪代码:
var globalVar;
Stateful Widget...
var _temp;
setState({_temp=yourData; globalVar=yourData})
doSomethingWithYourText(_temp != null ? _temp : globalVar)
当您将_temp
var用于所有布局更新时。 在状态重置(您更改为另一个视图)之前,globalVar更改将不明显。
因此,这是将您的数据保存在两个变量中,并检查状态是否曾经使用过。 如果不是,它将使用之前保存的var。
您需要使用PageStorage小部件和PageStoageBucket并将页面包装在PageStorage小部件内。
请参考本教程以获取更多详细信息:
在Dart的Flutter框架中保持UI状态并构建底部导航栏
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('嘿');
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.