在我的应用程序中,我想在挂载小部件时立即发出一个Ajax请求,而不是在initState()
中。类似于React中的componentWillMount()
。
initstate
中即可; void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) => yourFunction(context));
}
这样,yourFunction
函数将在小部件的第一帧加载到屏幕上时立即执行。
bool get mounted => _element != null;
这里是当_element
被设置时的情况:https://github.com/flutter/flutter/blob/master/packages/flutter/lib/src/widgets/framework.dart#L3816
_state._element = this
我没有看到任何钩子代码可以通知我们。
为什么不使用 initState
呢?这可能是您想要的。这是 mounted
属性上方的评论:https://github.com/flutter/flutter/blob/master/packages/flutter/lib/src/widgets/framework.dart#L967
/// After creating a [State] object and before calling [initState], the
/// framework "mounts" the [State] object by associating it with a
/// [BuildContext]. The [State] object remains mounted until the framework
只需按照以下步骤进行即可。
if (this.mounted) {
setState(() {
//Your code
});
}
在最新的更新中,Flutter 3.7,你可以直接使用context来检查widget是否已经挂载。以下是一个示例用法:
@override
Widget build(BuildContext context) {
return OutlinedButton(
onPressed: () async {
await Future<void>.delayed(const Duration(seconds: 1));
if (context.mounted) {
Navigator.of(context).pop();
}
},
child: const Text('Delayed pop'),
);
}
详情请参考此页面。
if(mounted){
setState(() {});
}
如果有任何更改,这将有助于仅重新构建UI。我自己在一个方法中使用它,从Firestore中填充用户列表。
mounted属性有助于避免在构建之前调用setState时出错。