flutter -- 创建移动应用程序时对象创建顺序是什么?

标签 flutter dart

假设应用程序的 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 ...

我很难弄清楚对象的创建顺序。我假设

  1. main() 首先运行,它
  2. 创建构成应用程序基础的 StatelessWidget MyApp 对象。当构建 MyApp 时,它
  3. 创建一个 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/

相关文章:

firebase - 参数不匹配的闭包调用 : function '[]' error is being shown in flutter

flutter - Flutter 是否有在移动和 Web 应用程序之间共享代码的好方法?

intellij-idea - IntelliJ更新后我无法加载dart/flutter插件

dart - 如何使用Dart包部署Dart Web应用程序?

dart - 如何在 Dart 控制台应用程序中收听键盘事件?

android - 类型 'Null' 不是类型 'Function' 的子类型

json - 如何访问 Dart 中对象列表中的对象列表

android - 我将如何画一条线来连接 flutter 中的点

flutter - FutureBuilder运行两次

encoding - 如何将代码页 1250 的字符串保存到 Dart 中的文件中?