【问题标题】:Why Statefull widget's build() function is called before initState()?为什么在 initState() 之前调用 Statefull 小部件的 build() 函数?
【发布时间】:2021-02-08 15:26:58
【问题描述】:

我创建了一个包装器来调用带有无状态小部件的 init():

class StatefulWrapper extends StatefulWidget {
  StatefulWrapper({this.child, this.init});
  final Widget child;
  final void Function() init;
  @override
  _StatefulWrapperState createState() => _StatefulWrapperState();
}

class _StatefulWrapperState extends State<StatefulWrapper> {
  @override
  void initState() {
    if (widget.init != null) widget.init();
    super.initState();
  }

  @override
  Widget build(BuildContext context) => widget.child ?? SizedBox();
}

下面是一个简单的使用示例:

class SomeView extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return StatefulWrapper(
      init: () => print('---------- step 1'),
      child: Scaffold(
        body: generateWidget(),
      ),
    );
  }
}

Widget generateWidget() {
  print('---------- step 2');
  return Container(width: 50, height: 50);
}

输出:

I/flutter ( 2810): ---------- step 2
I/flutter ( 2810): ---------- step 1

为什么 step2 在 step1 之前打印?

Flutter 1.22.2 稳定版

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    你错了。您的自己的构建函数不会在initState之前被调用。

    但是您的小部件需要一个完全构建的子组件和一个 init 函数。

    这需要 child 被构建 first 以作为参数传递。

    这就是你所看到的。

    【讨论】:

      猜你喜欢
      • 2020-06-07
      • 1970-01-01
      • 2021-08-16
      • 1970-01-01
      • 2019-07-12
      • 1970-01-01
      • 2020-07-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多