因此,在我的应用程序中,我想在安装小部件后立即发出 Ajax 请求,而不是在initState(). 类似ComponentWillMount()的反应
小智 23
如果 Widget 尚未安装,则返回。在setState方法之前做
if (!mounted) return;
setState(() {});
Run Code Online (Sandbox Code Playgroud)
或者
if (mounted) {
//Do something
};
setState(() {});
Run Code Online (Sandbox Code Playgroud)
Hos*_*adi 19
如果您想在小部件加载后立即执行某些代码,您可以简单地将此代码放入initstate如下所示;
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) => yourFunction(context));
}
Run Code Online (Sandbox Code Playgroud)
这样,一旦yourFunction窗口小部件的第一帧加载到屏幕上,就会执行。
我认为目前不可能。
这是mounted属性:https://github.com/flutter/flutter/blob/master/packages/flutter/lib/src/widgets/framework.dart#L974
bool get mounted => _element != null;
Run Code Online (Sandbox Code Playgroud)
这是_element设置的时间:https://github.com/flutter/flutter/blob/master/packages/flutter/lib/src/widgets/framework.dart#L3816
_state._element = this
Run Code Online (Sandbox Code Playgroud)
我没有看到这段代码有任何可以告诉我们的信息。
为什么不使用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
Run Code Online (Sandbox Code Playgroud)
只需按如下方式执行此操作即可。
if (this.mounted) {
setState(() {
//Your code
});
}
Run Code Online (Sandbox Code Playgroud)
小智 6
在最新的更新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'),
);
}
Run Code Online (Sandbox Code Playgroud)
详情请参阅此页。
| 归档时间: |
|
| 查看次数: |
16750 次 |
| 最近记录: |