• 11 个 Flutter 最佳实践


    11 个 Flutter 最佳实践

    alt

    学习最佳实践,用 Flutter 提高代码质量、可读性、可维护性和生产率。

    1. 将代码重构为 widgets 而不是 methods

    重构成一个方法可能看起来很诱人,但是当构建方法太大时,它可能会重新构建,即使构建方法内部没有任何更改。但是,当涉及到重构到一个 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,
             ),
           ),
         ),
       ],
     )
    • 1
    //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,
        ),
      ),
    );
    • 1
    • 2
    • 3
    • 4

    2. 尽可能使用 const 关键字

    当我们使用 setState() Flutter 调用 build 方法并重新构建其中的每个 widgets 树。避免这种情况的最佳方法是使用常量构造函数。

    在构建自己的 widgets 或使用 Flutter widgets 时,尽可能使用 const 构造函数。这有助于 Flutter 只重新构建应该更新的 widgets。

  • 相关阅读:
    2023数学建模国赛选题建议及BC题思路
    煤炉、Newegg测评自养号环境搭建技术
    常见Web安全
    研究生英语复习(一)
    使用Python自动发送邮件
    BI系统打包Docker镜像及部署的技术难度和实现
    21天打卡挑战 - 经典算法之快速排序
    使用OpenPCDet实现VoxelNext进行训练和测试:实现NuScence数据集的全局感知结果可视化
    next.js app目录 i18n国际化简单实现
    在Jupyter 中 from XXX import * 报错
  • 原文地址:https://blog.csdn.net/weixin_42320543/article/details/127549345