本文分享我在flutter编程中的重要技巧,学会了您的代码风格将得到很大提高。
下面的列子展示了如何用字符串乘法打印圣诞树
void main() {
for (var i = 1; i <= 5; i++) {
print('🎄' * i);
}
}
// Output:
// 🎄
// 🎄🎄
// 🎄🎄🎄
// 🎄🎄🎄🎄
// 🎄🎄🎄🎄🎄
是不是很酷? 😉
你可以用它来检查在 Text
widget中文本的长度是否合适。
Text('You have pushed the button this many times:' * 5)
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是「独立的」并且不需要「顺序」执行时,这样做起来就很理想。
下面是一个 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');
在下面的列子中我们定义了一个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();
}
在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();
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 操作符 (...
)。
.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}');
}
比如我们要定义一个温度的类。
需要让我们的类支持「两个」摄氏和华氏两种命名构造函数:
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);
在上面的 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 来改进类的设计。
举一个常见的列子 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,
)
注意*: 这两个参数是不同的 (_
和 __
) ,它们是「单独的标识符。」*
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
注意:如果不小心,单例可能会导致很多问题。在使用它们之前,请确保您了解它们的缺点。
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'});
当我们使用基于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时,一定要确保异常处理
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
表示错误。
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
创建周期性的事件流。我们可以定义一个 「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 应用程序中的代码。大家可以留言告诉我,你们最喜欢哪个小技巧!!