gpt4 book ai didi

flutter - 为什么在initState()之前调用有状态的小部件build()函数?

转载 作者:行者123 更新时间:2023-12-03 03:48:37 24 4
gpt4 key购买 nike

我创建了一个包装器,以使用无状态小部件调用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
为什么在步骤1之前打印步骤2?
flutter 1.22.2稳定

最佳答案

你误会了。您自己的构建函数不会在initState之前调用而不是
但是您的小部件需要一个完整的子代和一个init函数。
这就要求先构建子项以将其作为参数传递。
那就是你所看到的。

关于flutter - 为什么在initState()之前调用有状态的小部件build()函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64536002/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com