Flutter:滑动后默认选项卡栏控制器不保持状态 [英] Flutter: Default Tab Bar Controller does not maintain state after swipe
问题描述
我正在用flutter编写具有4个选项卡式视图的应用程序,有点像普通的android手机应用程序或时钟应用程序。这些视图之一散列了一个浮动操作按钮,按下该按钮将在列表中添加一些文本。但是,当我滚动到其他视图之一并返回时,所有文本都消失了。有解决办法吗?
I am writing an application in flutter that has 4 tabbed views, kinda like the stock android phone app or clock app. One of those views hash a floating action button that when pressed will add some text in a list. However, when I scroll to one of the other views and come back, all of the text is gone. Is there a way to fix this?
这是我的代码:
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
You need to use AutomaticKeepAliveClientMixin over your stateful widget and implement override method called wantKeepAlive
class MyApp extends StatefulWidget {
@override
createState() => new MyAppState();
}
将AutomaticKeepAliveClientMixin与您的类扩展状态和ov一起使用
use AutomaticKeepAliveClientMixin with your class extending state and 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......
}
在将wantKeepAlive设置为true时,initState方法在创建时将只运行一次。
on setting wantKeepAlive to true, initState method will run only once, at the time of creation.
这篇关于Flutter:滑动后默认选项卡栏控制器不保持状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!