学习最佳实践,用 Flutter 提高代码质量、可读性、可维护性和生产率。
重构成一个方法可能看起来很诱人,但是当构建方法太大时,它可能会重新构建,即使构建方法内部没有任何更改。但是,当涉及到重构到一个 widgets 时,我们得到了 widgets 生命周期的所有好处,因此只有当 widgets 中的某些内容发生变化时,它才会重新构建。因此,这可以防止不必要的重新构建,从而提高性能。这也提供了 Flutter 为 widgets 类提供的所有优化。
Column(
children: [
Container(
decoration: const BoxDecoration(
color: Colors.red,
),
child: const Text(
'Refactor to Widget',
style: TextStyle(
color: Colors.white,
),
),
),
],
)
//Do
class RefactorWidget extends StatelessWidget {
const RefactorWidget({
Key? key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
decoration: const BoxDecoration(
color: Colors.red,
),
child: const Text(
'Refactor to Widget',
style: TextStyle(
color: Colors.white,
),
),
);
}
}
//Do not
Container buildRefactorWidget() => Container(
decoration: const BoxDecoration(
color: Colors.red,
),
child: const Text(
'Refactor to Widget',
style: TextStyle(
color: Colors.white,
),
),
);
当我们使用 setState() Flutter 调用 build 方法并重新构建其中的每个 widgets 树。避免这种情况的最佳方法是使用常量构造函数。
在构建自己的 widgets 或使用 Flutter widgets 时,尽可能使用 const 构造函数。这有助于 Flutter 只重新构建应该更新的 widgets。