我正在用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,
),
);
}
}
答案 0 :(得分:4)
您需要在有状态窗口小部件上使用 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方法在创建时将只运行一次。
答案 1 :(得分:2)
答案 2 :(得分:2)
您需要使用PageStorage小部件和PageStoageBucket并将页面包装在PageStorage小部件中。
有关更多详细信息,请参阅本教程:
Persisting UI State and Building Bottom Navigation Bars in Dart's Flutter Framework
答案 3 :(得分:0)
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('嘿');
}
}