网站首页 > 博客文章 正文
本文分享我在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 应用程序中的代码。大家可以留言告诉我,你们最喜欢哪个小技巧!!
猜你喜欢
- 2025-05-23 Flutter——路由
- 2025-05-23 flutter软件开发笔记18-线程管理
- 2025-05-23 Flutter TextField 边框样式以及提示文本
- 2025-05-23 Flutter缓存数据可以怎么做
- 2025-05-23 flutter软件开发笔记20-flutter web开发
- 2025-05-23 flutter软件开发笔记25-内置组件总结
- 2025-05-23 flutter软件开发笔记17-isolate的机制作用
- 2025-05-23 Flutter实战经验(十二):不同平台操作体验的差异和适配(一)
- 2025-05-23 Flutter GetX 硬核分享:Rx 扩展方法实践指南
- 2025-05-23 Flutter与Android iOS 的双向通信
你 发表评论:
欢迎- 380℃手把手教程「JavaWeb」优雅的SpringMvc+Mybatis整合之路
- 375℃用AI Agent治理微服务的复杂性问题|QCon
- 375℃IT全明星|IntelliJ IDEA学习笔记(四、idea中怎么创建maven项目)
- 366℃初次使用IntelliJ IDEA新建Maven项目
- 359℃Maven技术方案最全手册(mavena)
- 356℃安利Touch Bar 专属应用,让闲置的Touch Bar活跃起来!
- 354℃InfoQ 2024 年趋势报告:架构篇(infoq+2024+年趋势报告:架构篇分析)
- 353℃IntelliJ IDEA 2018版本和2022版本创建 Maven 项目对比
- 最近发表
- 标签列表
-
- powershellfor (55)
- messagesource (56)
- aspose.pdf破解版 (56)
- promise.race (63)
- 2019cad序列号和密钥激活码 (62)
- window.performance (66)
- qt删除文件夹 (72)
- mysqlcaching_sha2_password (64)
- ubuntu升级gcc (58)
- nacos启动失败 (64)
- ssh-add (70)
- jwt漏洞 (58)
- macos14下载 (58)
- yarnnode (62)
- abstractqueuedsynchronizer (64)
- source~/.bashrc没有那个文件或目录 (65)
- springboot整合activiti工作流 (70)
- jmeter插件下载 (61)
- 抓包分析 (60)
- idea创建mavenweb项目 (65)
- vue回到顶部 (57)
- qcombobox样式表 (68)
- vue数组concat (56)
- tomcatundertow (58)
- pastemac (61)
本文暂时没有评论,来添加一个吧(●'◡'●)