如何在Flutter的Scaffold.drawer中保持小部件的状态? [英] How to keep the widget's state in Scaffold.drawer in Flutter?
问题描述
我想将小部件的状态保持在Scaffold.drawer
中. The Scaffold.drawer
是自定义窗口小部件,其中具有 RaiseButton .
当单击按钮时,按钮中的文本更改.
但是当抽屉关闭后,重新打开抽屉时,更改后的文本将被重置.
I want to keep the widget's state in Scaffold.drawer
. The Scaffold.drawer
is a custom widget, which has a RaiseButton in it.
When click the button, the text in the button changed.
But when the drawer is closed, and reopen the drawer, the changed text is reseted.
我在自定义的 Drawer 中使用了"with AutomaticKeepAliveClientMixin<>
",但是它不起作用.
I have use " with AutomaticKeepAliveClientMixin<>
" in my custom Drawer, but it does't work.
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key}) : super(key: key);
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Flutter Demo"),
),
drawer: Drawer(child: CustomDrawer(),),
body: Center(
child: Text("Flutter Demo"),
),
);
}
}
class CustomDrawer extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _CustomDrawerState();
}
}
class _CustomDrawerState extends State<CustomDrawer> with AutomaticKeepAliveClientMixin<CustomDrawer> {
String btnText = "Click!";
@override
bool get wantKeepAlive => true;
@override
Widget build(BuildContext context) {
super.build(context);
return Center(
child: RaisedButton(onPressed: () {
setState(() {
btnText = "Clicked!!";
});
}, child: Text(btnText),),
);
}
}
我希望即使关闭了抽屉,小部件的状态也可以保留.
I expect the widget's state can keep, even if the Drawer is closed.
推荐答案
在您的情况下,您有2个选择:
In your case, you have 2 choices:
- 您应将状态保留在顶级"小部件中.就您而言
_MyHomePageState
; - 使用状态管理器,例如
Redux
,Bloc
,ScopedModel
.在这种情况下,我认为ScopedModel
对您而言非常有用.
- You should keep your state in your Top level widget. in your case
_MyHomePageState
; - Use state managers like
Redux
,Bloc
,ScopedModel
. I thinkScopedModel
is great for you in this case.
否则,您将无法控制Drawer
的状态.导致每当您通过Appbar
中的操作按钮调用Drawer
时,它都会重新创建;
otherwise, you can't control the state of Drawer
. cause it re-creates every moment you call the Drawer
by the action button in Appbar
;
这篇关于如何在Flutter的Scaffold.drawer中保持小部件的状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!