Flutter 最佳实践
  xx2YH4ad7R0N 2023年11月02日 38 0


学习最佳实践,用 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,
),
),
),
],
)
//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,
),
),
);

2. 尽可能使用 const 关键字

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

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

3. 使用级联运算符

如果我们应该对同一个对象执行一系列操作,那么我们应该选择级联 ​​..​​ 接线员。

//Do
var path = Path()
..lineTo(0, size.height)
..lineTo(size.width, size.height)
..lineTo(size.width, 0)
..close();

//Do not
var path = Path();
path.lineTo(0, size.height);
path.lineTo(size.width, size.height);
path.lineTo(size.width, 0);
path.close();

4. 使用 spread collections

当现有项目已经存储在另一个集合中时,可以使用扩展集合,因为扩展集合语法使代码更简单、更容易。

//Do
var y = [4,5,6];
var x = [1,2,...y];

//Do not
var y = [4,5,6];
var x = [1,2];
x.addAll(y);

5. 使用 Null safe (??) 和 Null aware (?.) 操作符

在条件表达式中始终使用 ​​??​​​ (如果为空)和 ​​?.​​ (为空)运算符而不是空检查。

//Do
z = x ?? y;

//Do not
z = x == null ? y : x;

6. 避免使用 “as” 操作符代替 “is” 操作符

通常,如果无法进行强制转换,则 as 强制转换操作符将引发异常。若要防止引发异常,可以使用。

//Do
if (item is User)
item.name = 'Amir';

//Do not
(item as User).name = 'Amir';

7. 不要显式初始化变量 null

在 Dart 中,当没有指定变量的值时,该变量直观地初始化为 ​​null​​,因此添加 null 是多余的,不需要。

//Do
int counter;

//Do not
int counter = null;

8. 在 Flutter 使用 SizedBox 代替 Container

Container 是一个非常棒的 widgets,您将在 Flutter 广泛使用它。 ​​Container()​​​ 扩展到适合父节点给出的约束,并且不是常量构造函数。相反,​​SizedBox​​​ 是一个常量构造函数,构建一个固定大小的盒子。宽度和高度参数可以为 ​​null​​​,以指定不应在相应的维度中约束盒子的大小。因此,当我们必须实现占位符时,应该使用 ​​SizedBox​​​,而不是使用 ​​Container​​。

// Do
return _isNotLoaded ? SizedBox.shrink() : YourWidget();

//Do not
return _isNotLoaded ? Container() : YourWidget();

9. 使用 raw 字符串

可以使用原始字符串来避免只转义反斜杠和美元。

//Do
var s = r'This is example of raw string \ and $';

//Do not
var s = 'This is example of raw string \\ and \$';
复制代码

10. 变量命名原则

Dart 有三种变数命名原则。

  1. UpperCamelCase 大骆驼峰
  2. lowerCamelCase 小骆驼峰
  3. lowercase_with_underscores 下划线连词

UpperCamelCase 大骆驼峰

// 类名
Classes ( eg:- MyClass )
class MyClass { … }

// 枚举
enum ( eg:- Status )
enum Status { none, running, stopped, paused }

// 类型定义
typedefs ( eg:- Signature )
typedef Signature<T> = bool Function(T value);

// 泛型名
type parameters ( eg:- T )
class Foo<T extends Object> { … }

// 扩展
extension ( eg:- MyMethod )
extension MyMethod<T> on List<T> { … }

lowercase_with_underscores 下划线连词

//packages 包
eg:- hive_flutter, url_launcher, flutter_svg

//directories (mostly lowercase only) 目录
eg:- lib, bin, src, test, example

//source files 文件
eg:- main.dart, home.dart

//import prefixes 导包
eg:- import 'dart:math' as math;
eg:- import 'dart:math' as my_math;

lowerCamelCase 小骆驼峰

// 内部类 变量
// Class members (instance/static methods and variables)
eg:- void myFun() {}, int studentRank = 1;

// top-level definitions
eg:- double topVariable;

// variables
eg:- int myValue = 3;

// parameters (both positional and named)
eg:- void fun({int myParam}){…} , void fun(int myParam) {…}

11. 使用 if 代替三元运算符语法, 在如下情况

当设计一个 Flutter 应用程序时,通常情况下需要有条件地呈现不同的 widgets。您可能需要基于该平台生成一个 widgets,例如:

Row(
children: [
Text("Amir"),
Platform.isAndroid ? Text("This is From Android") : SizeBox(),
Platform.isIOS ? Text("This is From IOS") : SizeBox(),
]
);

在这种情况下,您可以删除三元运算符,并利用 Dart 的内置语法在数组中添加 if 语句。

Row(
children: [
Text("Amir"),
if (Platform.isAndroid) Text("This is From Android"),
if (Platform.isIOS) Text("This if From IOS"),
]
);
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
  iD7FikcuyaVi   2023年11月30日   26   0   0 MacWindowsandroid
  b1UHV4WKBb2S   2023年11月13日   37   0   0 裁剪ideflutter
  b1UHV4WKBb2S   2023年11月13日   29   0   0 flutterDart
xx2YH4ad7R0N