【发布时间】:2021-04-22 12:02:59
【问题描述】:
我一直在学习处理颤振中的async 函数。我已经定义了一个async 函数,并在两个地方调用了它
1。来自build 函数。
2。来自initState。
当从build 函数调用时,函数会被执行并将文本打印到终端,但是,从initstate 调用它时,终端不会记录任何文本。
这是代码。
import 'package:flutter/material.dart';
void main() => runApp(Test());
class Test extends StatefulWidget {
@override
_TestState createState() => _TestState();
}
class _TestState extends State<Test> {
@override
void initState() {
random();
// TODO: implement initState
super.initState();
}
@override
Widget build(BuildContext context) {
// random();
return MaterialApp(home: Scaffold(body: Center(child: Text("Wattup"))));
}
Future<void> random() async {
await Future.delayed(Duration(seconds: 2));
print("I'm Back baby");
}
}
【问题讨论】:
-
虽然通常应该首先调用
super.initState(),但您的代码应该可以工作-我的意思是从initState调用random()-我刚刚在一分钟前验证过-@987654333之后的print()@ 被调用,我在日志输出中看到它 -
我 99% 确定您已将
random()添加到initState()并按下“热重载”按钮,对吗? -
基本上如果你对现有的
StatefulWidget进行热重载initState不会被调用,但是如果你热重启它会被调用并且你的random()方法也会被调用 -
更多:flutter.dev/docs/development/tools/… - 搜索
What is the difference between hot reload, hot restart, and full restart?- 例如:“热重载将代码更改加载到 VM 并重新构建小部件树,保留应用程序状态; 它不会重新运行 main() 或 initState()。(在 Intellij 和 Android Studio 中为⌘\,在 VSCode 中为 ⌃F5)" -
正如我所说,如果你在
super.initState()之前或之后添加它,你的函数应该可以工作,但“正常”的方法是先调用super东西,然后是你的额外代码