【问题标题】:How to update the drawer content only如何仅更新抽屉内容
【发布时间】:2020-10-15 17:19:39
【问题描述】:

我们使用抽屉来显示“设置”状态。我希望用户能够更改设置并查看抽屉中反映的结果。

但是当我调用 setState 时,它​​会更新父窗口,而不是 Drawer 状态。

我希望用户能够将通知从“无”更改为“电话”并查看抽屉状态中的反映。但它总是显示原始价值。

  @override
  Widget build(BuildContext context) {
    var key = GlobalKey<ScaffoldState>();
    return Scaffold(
      key: key,
      body: Text("Test Data"),
      bottomNavigationBar: NavBar(),
      drawer: Drawer( child: components( context ) ),
    );
  }

Widget components( context )
  {
    return ListView(
      children: <Widget>[
        ListTile( dense: true, leading: Icon(Icons.notifications), title: Text("Notifications"),
            trailing: DropdownButtonHideUnderline ( child: DropdownButton<String>(
              value: Settings.notifications.toString().split('.')[1],
              icon: Icon(Icons.expand_more),
              onChanged: (String newValue) {
                if ( 'none' == newValue )
                  Settings.notifications = Notifications.none;
                else if ( 'email' == newValue )
                  Settings.notifications = Notifications.email;
                else if ( 'phone' == newValue )
                  Settings.notifications = Notifications.phone;
                else
                  Settings.notifications = Notifications.both;
                setState(() {
                });
              },
              items: <String>['none','email','phone','both']
                  .map<DropdownMenuItem<String>>((String value) {
                return DropdownMenuItem<String>( value: value, child: Text(value), );
              }).toList(),
            ) ),),
          ],
        );
    }

【问题讨论】:

  • 所以选择后你想更改默认文本?

标签: flutter setstate drawer


【解决方案1】:

Drawer 本身就是一个无状态小部件

将小部件代码放在函数中不会为其提供单独状态。它本质上是 Main Widget 的一部分,因此 setState() 调用位于 Main Widget 下。

创建一个单独的StatefulWidget(比如MyStatefulDrawer),并将您的抽屉小部件代码放在那里,Drawer 类作为根小部件。

现在,在您的主窗口小部件中使用MyStatefulDrawer

@override
  Widget build(BuildContext context) {
    var key = GlobalKey<ScaffoldState>();
    return Scaffold(
      key: key,
      body: Text("Test Data"),
      bottomNavigationBar: NavBar(),
      drawer: MyStatefulDrawer(context),
    );
  }

现在您的抽屉是有状态的,您可以在其中 setState() 并使用更新后的值重建它。

【讨论】:

  • 这对于有状态的行为是有意义的。并且在实施时,它会表现出所需的行为。然而,它不再充当“抽屉”,即仅覆盖屏幕的一部分并自动消失。你知道如何模仿这种行为吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-02-10
  • 2020-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-03
  • 1970-01-01
相关资源
最近更新 更多