Dart:在循环中使用 Async 和 Await
在 Dart(以及 Flutter)中,您可以使用Future.forEach在循环中顺序执行同步操作。下面的示例程序将打印从 1 到 10 的数字。每次打印完一个数字,它会等待 3 秒,然后再打印下一个数字。
//大前端之旅
void main() async {
final items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
await Future.forEach(items, (item) async {
print(item);
await Future.delayed(const Duration(seconds: 3));
});
}
另一种方法是在语法中使用for ... ,如下所示:
// 大前端之旅
void main() async {
final items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for (int item in items) {
print(item);
await Future.delayed(const Duration(seconds: 3));
}
}
Flutter & Dart:将字符串转换为列表,反之亦然
在 Flutter 和 Dart 中,您可以使用split() 方法将给定的字符串转换为列表(带有字符串元素)。
例子:
// main.dart
void main() {
const String s =
"blue red orange amber green yellow purple pink brown indigo";
final List<String> colors = s.split(' ');
print(colors);
}
输出:
[blue, red, orange, amber, green, yellow, purple, pink, brown, indigo]
要将字符串列表转换为字符串,可以使用join()方法。
例子:
flutter开发零
// main.dart
void main() {
final List<String> list = [
'dog',
'cat',
'dragon',
'pig',
'monkey',
'cricket'
];
final String result = list.join(', ');
print(result);
}
输出:
dog, cat, dragon, pig, monkey, cricket
进一步阅读:
- Dart:从给定字符串中提取子字符串(高级)
- Dart 正则表达式来检查人的名字
- Flutter & Dart:正则表达式示例
- Dart 和 Flutter 中的排序列表(5 个示例)
- Flutter 表单验证示例
您还可以浏览我们的Flutter 主题页面和Dart 主题页面,查看最新的教程和示例。