百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 编程字典 > 正文

每个flutter开发人员都要知道的16个dart技巧

toyiye 2024-07-06 00:31 12 浏览 0 评论

本文分享我在flutter编程中的重要技巧,学会了您的代码风格将得到很大提高。

1. 你知道吗,Dart 支持字符串乘法。

下面的例子如何用字符串乘法打印圣诞树

void main() {
  for (var i = 1; i <= 5; i++) {
    print('' * i);
  }
}
// Output:
// 
// 
// 
// 
// 

是不是很酷?

你可以用它来检查在 Text widget中文本的长度是否合适。

Text('You have pushed the button this many times:' * 5)

2. 需要同时执行多个Future? 使用 Future.wait.

Consider this mock API class that tells us the latest numbers of COVID cases:

// Mock API class
class CovidAPI {
  Future<int> getCases() => Future.value(1000);
  Future<int> getRecovered() => Future.value(100);
  Future<int> getDeaths() => Future.value(10);
}

要同时执行这些future, 使用 Future.wait。参数需要 「futures」 的list并且会返回一个 「future」「list」:

final api = CovidAPI();
final values =await Future.wait([
    api.getCases(),
    api.getRecovered(),
    api.getDeaths(),
]);
print(values); // [1000, 100, 10]

当Future是「独立的」并且不需要「顺序」执行时,这样做起来就很理想。

3. 可以在Dart的class中实现一个 “call”方法,这样我们就可以像调用方法一样调用类。

下面是一个 PasswordValidator class:

class PasswordValidator {
  bool call(String password) {
    return password.length > 10;
  }
}

我们定义了一个call 方法, 再定义一个类的实例就可以像使用函数一样使用它:

final validator = PasswordValidator();
// can use it like this:
validator('test');
validator('test1234');
// no need to use it like this:
validator.call('not-so-frozen-arctic');

4. 需要调用回调方法,但前提是回调方法不为空?使用 "?.call()" 语法。

在下面的列子中我们定义了一个widget,并且要在事件触发时调用onDragCompleted 回调:

class CustomDraggableextends StatelessWidget {
  const CustomDraggable({Key key, this.onDragCompleted}) : super(key: key);
final VoidCallback? onDragCompleted;


  void _dragComplete() {
    // TODO: Implement me
  }
  @override
  Widget build(BuildContext context) {/*...*/}
}

为了调用回调函数,我们可能要写如下的代码:

  void _dragComplete() {
    if (onDragCompleted != null) {
      onDragCompleted();
    }
  }

但是我们可以使用如下的简单语法 (使用 ?.):

  Future<void> _dragComplete()async {
    onDragCompleted?.call();
  }

5. 使用匿名函数和函数作为参数

在Dart中, 函数是一等公民,并且能够作为其他函数的参数。

下面演示了定义一个匿名函数,并且赋值给 sayHi 变量:

void main() {
  final sayHi = (name) => 'Hi, $name';
  welcome(sayHi, 'Andrea');
}


void welcome(String Function(String) greet, String name) {
  print(greet(name));
  print('Welcome to this course');
}

将 sayHi 作为变量传给 welcome 方法的greet参数。

String Function(String) 是 一个函数「类型」 ,带有 String 参数 并且返回 String类型。 因为上面的匿名函数具有相同的 「signature」, 所以能够直接作为参数传递。


在list的 map, where, reduce 等操作时,这样的代码风格很常见。

举个计算数的平方的例子:

int square(int value) {
  // just a simple example
  // could be a complex function with a lot of code
  return value * value;
}

计算出数组的所有平方:

const values = [1, 2, 3];


values.map(square).toList();

这里使用 square 作为参数,因为square的 signature是符合map 操作期望的。所以我们可以不使用下面的匿名函数:

values.map((value) => square(value)).toList();

6. 可以将 collection-if 和 spreads 与列表、集合和map一起使用

Collection-if and spreads 在我们写代码时非常有用。

这些其实也可以和map一起使用。

看下面的例子:

const addRatings = true;
const restaurant = {
  'name' : 'Pizza Mario',
  'cuisine': 'Italian',
  if (addRatings) ...{
    'avgRating': 4.3,
    'numRatings': 5,
  }
};

我们定义了一个 restaurant 的map, 并且只有当 addRatings 是 true的时候才会添加 avgRating and numRatings 。 因为超过了一个key-value,所以需要使用 spread 操作符 (...)。

7. 如何以 null-safe的方法遍历整个map? 使用.entries:

看下面的一个例子:

const timeSpent = <String, double>{
  'Blogging': 10.5,
  'YouTube': 30.5,
  'Courses': 75.2,
};

下面是循环遍历key-value:

for (var entry in timeSpent.entries) {
  // do something with keys and values
  print('${entry.key}: ${entry.value}');
}

8. 使用命名构造函数 和 初始化列表使API更简洁.

比如我们要定义一个温度的类。

需要让我们的类支持「两个」摄氏和华氏两种命名构造函数:

class Temperature {
  Temperature.celsius(this.celsius);
  Temperature.fahrenheit(double fahrenheit)
    : celsius = (fahrenheit - 32) / 1.8;
  double celsius;
}

该类只需要一个变量来表示温度,并使用初始化列表将华氏温度转换为摄氏温度。

我们在使用时就可以像下面这样:

final temp1 = Temperature.celsius(30);
final temp2 = Temperature.fahrenheit(90);

9. Getters and setters

在上面的 Temperature 类中, celsius 用来表示温度。

但是有些用户可能喜欢华氏温度。

我们可以很容易通过getters and setters实现, 定义 computed 变量(学过vue的是不是感觉很熟悉). 继续看下面的例子:

class Temperature {
  Temperature.celsius(this.celsius);
  Temperature.fahrenheit(double fahrenheit)
    : celsius = (fahrenheit - 32) / 1.8;
  double celsius;
  double get fahrenheit
    => celsius * 1.8 + 32;
  set fahrenheit(double fahrenheit)
    => celsius = (fahrenheit - 32) / 1.8;
}

这下我们使用华氏温度或者摄氏温度就很容易了:

final temp1 = Temperature.celsius(30);
print(temp1.fahrenheit);
final temp2 = Temperature.fahrenheit(90);
temp2.celsius = 28;

提示: 使用命名构造函数、getter 和 setter 来改进类的设计。

10. 未使用的参数使用下划线表示

举一个常见的例子 ListView.builder:

class MyListView extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemBuilder: (context, index) => ListTile(
        title: Text('all the same'),
      ),
      itemCount: 10,
    );
  }
}

上面的例子中我们没有使用itemBuilder的的参数 (context, index) 。因此我们可以使用下划线代替。

ListView.builder(
  itemBuilder: (_, __) => ListTile(
    title: Text('all the same'),
  ),
  itemCount: 10,
)

注意*: 这两个参数是不同的 (_ 和 __) ,它们是「单独的标识符。」*

11. 一个类只需要被初始化一次 (单例模式)? 使用带有私有构造函数的静态实例变量。

The most important property of a singleton is that there can only be 「one instance」 of it in your entire program. This is useful to model things like a file system.

// file_system.dart
class FileSystem {
  FileSystem._();
  static final instance = FileSystem._();
}

要在 Dart 中创建单例,您可以声明一个命名构造函数并使用_语法将其设为私有。

然后再定一个final类型的类静态实例。

从此,只能通过instance变量访问这个类。

// some_other_file.dart
final fs = FileSystem.instance;
// do something with fs

注意:如果不小心,单例可能会导致很多问题。在使用它们之前,请确保您了解它们的缺点。

12. 想要集合中的每一项都是唯一的? 使用Set而不是 List。

Dart中最常见的集合是 List.

list可以有重复的项, 有些时候我们想要元素是唯一的:

const citiesList = [
  'London',
  'Paris',
  'Rome',
  'London',
];

这时候我们就需要使用 Set (注意我们使用了 final):

// set is final, compiles
final citiesSet = {
  'London',
  'Paris',
  'Rome',
  'London', // Two elements in a set literal shouldn't be equal
};

上面的代码将产生警告,因为 London 包含了两个. 如果把set定义为 const ,代码将产生错误,并且不能编译成功:

// set is const, doesn't compile
const citiesSet = {
  'London',
  'Paris',
  'Rome',
  'London', // Two elements in a constant set literal can't be equal
};

我们使用set时,我们可以使用 union, difference, and intersectio等API

citiesSet.union({'Delhi', 'Moscow'});
citiesSet.difference({'London', 'Madrid'});
citiesSet.intersection({'London', 'Berlin'});

13. 怎么使用 try, on, catch, rethrow, finally

当我们使用基于Future的API时,try 和 catch 是非常有用的。

看看下面的例子:

Future<void> printWeather() async {
  try {
    final api = WeatherApiClient();
    final weather = await api.getWeather('London');
    print(weather);
  } on SocketException catch (_) {
    print('Could not fetch data. Check your connection.');
  } on WeatherApiException catch (e) {
    print(e.message);
  } catch (e, st) {
    print('Error: $e\nStack trace: $st');
    rethrow;
  } finally {
    print('Done');
  }
}

有以下几点需要主要:

  • 可以添加多个on 来捕获不同类型的异常。
  • 最后可以添加一个 catch 来捕获上面没有处理到的异常.
  • 使用rethrow语句将当前异常抛出调用堆栈,「同时保留堆栈追踪。」
  • 使用finally在Future完成后运行一些代码,无论它是成功还是失败。

使用Future相关的API时,一定要确保异常处理

14. Future的一些常用构造函数

Future中有一些方便的构造函数:Future.delayed,Future.value和Future.error。

我们可以使用Future.delayed 制造一定的延迟。第二个参数是一个(可选的)匿名函数,可以用它来完成一个值或抛出一个错误:

await Future.delayed(Duration(seconds: 2), () => 'Latte');

有时我们可以创建一个 Future 并立即返回,这在测试mock数据时非常有用:

await Future.value('Cappuccino');
await Future.error(Exception('Out of milk'));

我们可以用Future.value一个值来表示成功完成,或者Future.error表示错误。

15. 常见的 Stream 构造函数

Stream 类也带有一些方便的构造函数。以下是最常见的:

Stream.fromIterable([1, 2, 3]);
Stream.value(10);
Stream.empty();
Stream.error(Exception('something went wrong'));
Stream.fromFuture(Future.delayed(Duration(seconds: 1), () => 42));
Stream.periodic(Duration(seconds: 1), (index) => index);
  • 使用 Stream.fromIterable 从list创建Stream。
  • 使用 Stream.value 从一个单一值创建。
  • 使用 Stream.empty 创建一个空的stream。
  • 使用 Stream.error 包含错误值的stram。
  • 使用 Stream.fromFuture 创建一个只包含一个值的stream,并且该值将在未来完成时可用。
  • 使用 Stream.periodic 创建周期性的事件流。

16. Sync and Async Generators

我们可以定义一个 「synchronous」 generator(同步生成器) 函数的返回类型定义为 Iterable:

Iterable<int> count(int n) sync* {
  for (var i = 1; i <= n; i++) {
     yield i;
  }
}

这里使用了 sync* 语法. 在函数内部,我们可以yield多个值. 这些值将在函数完成时作为一个 Iterable 返回.


另外, 一个「asynchronous」 generator 需要使用 Stream作为返回值

Stream<int> countStream(int n)async* {
  for (var i = 1; i <= n; i++) {
     yield i;
  }
}

这里使用 async* 语法. 在函数内部,我们可以 yield 多个返回值。

「asynchronous」 generator中我们也可以使用Future相关的函数:

Stream<int> countStream(int n)async* {
  for (var i = 1; i <= n; i++) {
    // dummy delay - this could be a network request
    await Future.delayed(Duration(seconds: 1));
    yield i;
  }
}

最后

希望大家喜欢我提供的这写小技巧,快来使用它们来改进 Flutter 应用程序中的代码。大家可以留言告诉我,你们最喜欢哪个小技巧!!

相关推荐

为何越来越多的编程语言使用JSON(为什么编程)

JSON是JavascriptObjectNotation的缩写,意思是Javascript对象表示法,是一种易于人类阅读和对编程友好的文本数据传递方法,是JavaScript语言规范定义的一个子...

何时在数据库中使用 JSON(数据库用json格式存储)

在本文中,您将了解何时应考虑将JSON数据类型添加到表中以及何时应避免使用它们。每天?分享?最新?软件?开发?,Devops,敏捷?,测试?以及?项目?管理?最新?,最热门?的?文章?,每天?花?...

MySQL 从零开始:05 数据类型(mysql数据类型有哪些,并举例)

前面的讲解中已经接触到了表的创建,表的创建是对字段的声明,比如:上述语句声明了字段的名称、类型、所占空间、默认值和是否可以为空等信息。其中的int、varchar、char和decimal都...

JSON对象花样进阶(json格式对象)

一、引言在现代Web开发中,JSON(JavaScriptObjectNotation)已经成为数据交换的标准格式。无论是从前端向后端发送数据,还是从后端接收数据,JSON都是不可或缺的一部分。...

深入理解 JSON 和 Form-data(json和formdata提交区别)

在讨论现代网络开发与API设计的语境下,理解客户端和服务器间如何有效且可靠地交换数据变得尤为关键。这里,特别值得关注的是两种主流数据格式:...

JSON 语法(json 语法 priority)

JSON语法是JavaScript语法的子集。JSON语法规则JSON语法是JavaScript对象表示法语法的子集。数据在名称/值对中数据由逗号分隔花括号保存对象方括号保存数组JS...

JSON语法详解(json的语法规则)

JSON语法规则JSON语法是JavaScript对象表示法语法的子集。数据在名称/值对中数据由逗号分隔大括号保存对象中括号保存数组注意:json的key是字符串,且必须是双引号,不能是单引号...

MySQL JSON数据类型操作(mysql的json)

概述mysql自5.7.8版本开始,就支持了json结构的数据存储和查询,这表明了mysql也在不断的学习和增加nosql数据库的有点。但mysql毕竟是关系型数据库,在处理json这种非结构化的数据...

JSON的数据模式(json数据格式示例)

像XML模式一样,JSON数据格式也有Schema,这是一个基于JSON格式的规范。JSON模式也以JSON格式编写。它用于验证JSON数据。JSON模式示例以下代码显示了基本的JSON模式。{"...

前端学习——JSON格式详解(后端json格式)

JSON(JavaScriptObjectNotation)是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。它基于JavaScriptProgrammingLa...

什么是 JSON:详解 JSON 及其优势(什么叫json)

现在程序员还有谁不知道JSON吗?无论对于前端还是后端,JSON都是一种常见的数据格式。那么JSON到底是什么呢?JSON的定义...

PostgreSQL JSON 类型:处理结构化数据

PostgreSQL提供JSON类型,以存储结构化数据。JSON是一种开放的数据格式,可用于存储各种类型的值。什么是JSON类型?JSON类型表示JSON(JavaScriptO...

JavaScript:JSON、三种包装类(javascript 包)

JOSN:我们希望可以将一个对象在不同的语言中进行传递,以达到通信的目的,最佳方式就是将一个对象转换为字符串的形式JSON(JavaScriptObjectNotation)-JS的对象表示法...

Python数据分析 只要1分钟 教你玩转JSON 全程干货

Json简介:Json,全名JavaScriptObjectNotation,JSON(JavaScriptObjectNotation(记号、标记))是一种轻量级的数据交换格式。它基于J...

比较一下JSON与XML两种数据格式?(json和xml哪个好)

JSON(JavaScriptObjectNotation)和XML(eXtensibleMarkupLanguage)是在日常开发中比较常用的两种数据格式,它们主要的作用就是用来进行数据的传...

取消回复欢迎 发表评论:

请填写验证码