• 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。

  • 相关阅读:
    基于Java+JSP+MySQL基于SSM的智能推荐商城系统-计算机毕业设计
    Apache Pulsar的分布式集群模式构建
    数组的子集不能累加出的最小正数
    处理Java异常的10个最佳实践
    【docker】docker容器与服务器时间区不一样【已解决】
    Liunx-02建立liunx实验环境
    0.0和0.00竟然不相等!!!BigDecimal别用错了比较方式
    第二章:02_单机版与控制台的安装和启动
    ES6中的函数
    vim 从嫌弃到依赖(19)——替换
  • 原文地址:https://blog.csdn.net/weixin_42320543/article/details/127549345