假设应用程序的 main.dart 文件包含以下代码:
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
Widget build(BuildContext context) {
return MaterialApp(
//theme, etc.,
home: StoryPage(),
);
}
}
SomeCustomClass myCustomClass = SomeCustomClass();
class StoryPage extends StatefulWidget {
_StoryPageState createState() => _StoryPageState();
}
class _StoryPageState extends State<StoryPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
//more code ...
我很难弄清楚对象的创建顺序。我假设
main()
首先运行,它- 创建构成应用程序基础的 StatelessWidget
MyApp
对象。当构建MyApp
时,它 - 创建一个 StatefulWidget
StoryPage
对象。
所有这些都准确吗?如果是这样,myCustomClass
何时实例化?
最佳答案
main()
总是第一个被调用的函数。它在您的应用程序中的任何其他 Dart 代码之前被调用。
所有顶级和静态对象都是在第一次访问时延迟创建的。为了演示,请尝试运行以下代码:
final Foo foo = Foo();
void main() {
print('hello');
foo.toString(); // Just to access foo.
}
class Foo {
Foo() { print('world'); }
}
如果顶级对象是在 main 之前构建的,那么您会看到“world\nhello”。相反,我们正确地看到了 hello\nworld
。
任何 const
对象都是“在编译时”创建的,因此不会在运行时创建对象。它们作为数据存在于程序的内存中。这当然无法观察到,因为 const 对象的构造在设计上不能有副作用。
关于flutter -- 创建移动应用程序时对象创建顺序是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57173859/