gpt4 book ai didi

flutter - 为什么热重启时构建函数会被调用两次?

转载 作者:行者123 更新时间:2023-12-04 13:11:19 26 4
gpt4 key购买 nike

我注意到 build 函数在无状态小部件中被调用了两次。

import 'package:flutter/material.dart';

void main() {
runApp(new MyApp());
}

class MyApp extends StatelessWidget {
MyApp() {
print("constructor MyApp class");
}

@override
Widget build(BuildContext context) {
print("build MyApp");
return MaterialApp(
home: HomeWidget(),
);
}
}

class HomeWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(child: Text("home widget")),
);
}
}
控制台结果
Performing hot restart...
Syncing files to device AOSP on IA Emulator...
Restarted application in 755ms.
I/flutter (14765): constructor MyApp class
I/flutter (14765): build MyApp
I/flutter (14765): build MyApp
从控制台输出中,构造函数被调用一次,构建函数被调用两次。
我搜索了这个问题并阅读了下面的文档。
Why Root Widget gets build twice?
https://github.com/flutter/flutter/issues/33566
https://flutterigniter.com/future-async-called-multiple-times/
不过,我不是很清楚。为什么多次调用构建函数?我没有使用异步或 future ,我的代码非常简单。
在 dartpad 上运行时不会出现此问题。它只发生在 android studio 中。

最佳答案

由于多种原因,构建方法可能会被多次调用。它不应该被视为问题,而是 Flutter 的工作原理。
Widget.build documentation状态:The framework calls this method when this widget is inserted into the tree in a given BuildContext and when the dependencies of this widget change. [...] This method can potentially be called in every frame and should not have any side effects beyond building a widget.还有这个response from the Flutter team在 GitHub 上的一个类似的已关闭问题上:Flutter does not guarantee Widget.build will be called the minimum number of times possible. You should structure your application in a way that assumes build will be called on every frame - anything less is an optimization.

关于flutter - 为什么热重启时构建函数会被调用两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64834702/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com