[译] 3个好玩的Dart模式

695 阅读2分钟

通过Flutter框架,您可以使用Dart编程语言来创建漂亮的应用程序,随着时间的推移,我学会了有用的dart的模式,这些模式昂护着我成为了更好的Flutter的开发人员。建议您尝试一下一下三种方法。

  • 有条件分配值 bool?widgetA:widgetB
  • 将小部件合并到集合中for()...[]
  • 匿名函数

本文展示如何使用这三种模式。

1.条件选择器

首先使用可选择值来展示数据,本例子根据haveTitle来判断,是否显示title.

 bool haveTitle = false;
  @override
  Widget build(BuildContext context) {
    DEBUG();
    return Scaffold(
      appBar: AppBar(
        title: Text(haveTitle ? widget.title : ''),
      ),
      body: Stack(
        children: <Widget>[
          Positioned.fill(
              child: Center(
            child: _widget(),
          )),
        ],
      ),
    );
  }

2.合并子部件到集合

这个模式,for()...[]使用了...操作符来合并一个list到已经存在的集合中,我开发过程中使用了数组存储了widget,在children的时候进行合并。

class Food {
  Food({this.show, this.name});
  String name;
  bool show;
}


@override
Widget build(BuildContext context) {
 List<Food> list = [
  Food(name: '苹果', show: true),
  Food(name: '香蕉', show: true),
  Food(name: '牛奶', show: false),
  Food(name: '梨', show: true),
];
return Scaffold(
  appBar: AppBar(
    title: Text(haveTitle ? widget.title : ''),
  ),
  body: Center(
    child: Column(
      children: [
        for (var i in list) ...[
          if (i.show == true)
            Container(
              child: Text(i.name),
            ),
          SizedBox(
            height: 20,
          )
        ]
      ],
    ),
  ),
);
}

show等于true则进行迭代了三次,展示了苹果、香蕉、梨这三个部件到部件数组中。

Dart 2.3.0以后就可以使用了,为了你在项目中可以使用的更好, 请再确认下yaml文件是这样配置的:

environment:
  sdk: ">=2.3.0 < 3.0.0"

3.立即匿名函数

第三种模式(){}(),等效于函数表达式IFFY,这种模式您可以定义一个匿名函数并立即执行他,他可以有多个小部件时候非常好用。该代码并不是三元运算符简化版本或者简单调用的模块化,而是可以内联使用。下面展示该模式,并带有一个switch语句的匿名函数。

color: () {
  switch (getRandomElement(foods).name) {
    case 'apple':
      return Colors.green;
    case 'nuts':
      return Colors.brown;
    case 'eggs':
      return Colors.yellow;
    default:
      return Colors.transparent;
  }
}(),

我希望这三种模式可以给你更多的自由开发,如果您有其他喜欢的模式,请在评论中分享。

想要了解更多信息,请通过github访问他。

参考: 原文链接:medium.com/dartlang/3-…