在子窗口小部件的构建方法设置父窗口小部件的状态后触发的回调不会触发其父窗口的构建方法

时间:2020-01-29 00:07:06

标签: flutter

我有一个父小部件(此代码段)称为MainLayout,还有一个子小部件ChildChild。我想在执行其构建方法后,在子级父级小部件的AppBar的操作中添加一个IconButton。父级的AppBar中显示的操作以其状态存储。

我使用的方法存在问题:子控件的build方法设置其父控件状态后触发的回调不会触发其父控件的构建方法,但是状态(父母的)已更改。结果,搜索图标未安装在MainLayout的AppBar动作中。

为什么要采用这种方式以及如何解决?

下面的代码是我的孩子和父母小部件外观的示例:

child_widget.dart

class ChildWidget extends StatelessWidget {
  // Add a search button in the AppBar of MainLayout widget.
  void _updateAppBar(BuildContext context) async {
    InheritedMainLayout.of(context).appBar.updateActions(<Widget>[
            IconButton(
              icon: Icon(Icons.search),
              onPressed: () => showSearch(
                context: context,
                delegate: SearchPageDelegate(),
              ),
            ),
          ]);
  }

  @override
  Widget build(BuildContext context) {
    _updateAppBar(context);
    return Container(
      width: 100,
      height: 100,
      color: Colors.blue,
    );
  }
}

parent_widget.dart

class ParentWidget extends StatefulWidget {
  @override
  _ParentWidgetState createState() => new _ParentWidgetState();
}

class _ParentWidgetState extends State<ParentWidget> {
  // This is the method that is passed as a parameter to the ChildWidget to update the actions of the AppBar.
  void _updateAppBarActions(List<Widget> actions) =>
    setState(() => _appBarActions = actions);

  @override
  Widget build(BuildContext context) {
    return InheritedMainLayout( // The inherited widget used to use the _updateAppBarActions method in the child widget
      appBar: new AppBarConfig(
        actions: _appBarActions,
      ),
      child: Scaffold(
        appBar: AppBar(
          title: Text("Title of the App"),
          actions: _appBarActions, // Actions showed in the AppBar are from the state, _appBarActions
        ),
        body: Padding(
          padding: EdgeInsets.all(20.0),
          child: _currentChild, // Here is loaded the builded widget called ChildWidget.
        ),
        drawer: AppDrawer(
          items: _drawerItems,
          onTap: _onChangePage,
        ),
      ),
    );
  }
}

1 个答案:

答案 0 :(得分:0)

您可能会看到此问题,因为在生成过程中无法调用setState。您可以在构建过程之后使用addPostFrameCallback方法调用回调。例如,请参见此问题的答案Calling setState() during build without user interaction