Foreword
| category | Keyword | Return type | partner |
|---|---|---|---|
| Multi-element synchronization | sync* | Iterable<T> |
yield、yield* |
| Single element | async | Future<T> |
await |
| Multi-element asynchronous | async* | Stream<T> |
yield、yield* 、await |
Let's take a few Emoji, meet these keywords.
First, multi-element synchronization function generator
1. sync* with yield
sync*Is a DART syntaxKeyword。It is marked before the function {, the method must return an ITerable <T> object
👿 code is\u{1f47f}. Below is usedsync*10 EMOJI after generatingItereable objectMethods
main() {
getEmoji(10).forEach(print);
}
Iterable<String> getEmoji(int count) sync* {
Runes first = Runes('\u{1f47f}');
for (int i = 0; i < count; i++) {
yield String.fromCharCodes(first.map((e) => e + i));
}
}
Copy code
👿
💀
💁
💂
💃
💄
💅
💆
💇
💈
Copy code
2、sync* with yield*
yield*Another do you have anyone? Remember a littleyield*The back expression is oneITERABLE <T> object
, for example,getEmojiThe method is the core, now you want to print each time, usegetEmojiWithTimeyield*AftergetEmoji(count).map((e)...It is an iterative objectIterable<String>
main() {
getEmojiWithTime(10).forEach(print);
}
Iterable<String> getEmojiWithTime(int count) sync* {
yield* getEmoji(count).map((e) => '$e -- ${DateTime.now().toIso8601String()}');
}
Iterable<String> getEmoji(int count) sync* {
Runes first = Runes('\u{1f47f}');
for (int i = 0; i < count; i++) {
yield String.fromCharCodes(first.map((e) => e + i));
}
}
Copy code
👿 -- 2020-05-20T07:01:07.163407
💀 -- 2020-05-20T07:01:07.169451
💁 -- 2020-05-20T07:01:07.169612
💂 -- 2020-05-20T07:01:07.169676
💃 -- 2020-05-20T07:01:07.169712
💄 -- 2020-05-20T07:01:07.169737
💅 -- 2020-05-20T07:01:07.169760
💆 -- 2020-05-20T07:01:07.169789
💇 -- 2020-05-20T07:01:07.169812
💈 -- 2020-05-20T07:01:07.169832
Copy code
Second, asynchronous treatment:asyncwithawait
asyncIs a DART syntaxKeyword。It is marked before the function {, the method must return a Future <T> object
Usually usedFuture<T>Object asynchronous processing, belowFetchemoji methodSimulation 2S loading time
main() {
print('Open -${DateTime.now().toIso8601String()}');
fetchEmoji(1).then(print);
}
Future<String> fetchEmoji(int count) async{
Runes first = Runes('\u{1f47f}');
await Future.delayed(Duration(seconds: 2));// Simulation time
print('Loading end -${DateTime.now().toIso8601String()}');
return String.fromCharCodes(first.map((e) => e + count));
}
Copy code
Load start --2020-05-20T07:20:32.156074
Load end --2020-05-20T07:20:34.175806
💀
Copy code
Third, multi-element asynchronous function generator:
1.async*withyield、await
async*Is a DART syntaxKeyword。It is marked before the function {, the method must return a stream <t> object
belowfetchEmojisBeasync*Note, so return it is inevitableStreamObject
NoteBeing async *The function of the label can be used inside it.yield、yield*、awaitKeyword
main() {
fetchEmojis(10).listen(print);
}
Stream<String> fetchEmojis(int count) async*{
for (int i = 0; i < count; i++) {
yield await fetchEmoji(i);
}
}
Future<String> fetchEmoji(int count) async{
Runes first = Runes('\u{1f47f}');
print('Load start -${DateTime.now().toIso8601String()}');
await Future.delayed(Duration(seconds: 2));// Simulation time
print('Loading end -${DateTime.now().toIso8601String()}');
return String.fromCharCodes(first.map((e) => e + count));
}
Copy code
Load start --2020-05-20T07:28:28.394205
Load end --2020-05-20T07:28:30.409498
👿
Load start --2020-05-20T07:28:30.416714
Load end --2020-05-20T07:28:32.419157
💀
Load start --2020-05-20T07:28:32.419388
Load end --2020-05-20T07:28:34.423053
💁
Load start --2020-05-20T07:28:34.423284
Load end --2020-05-20T07:28:36.428161
💂
Load start --2020-05-20T07:28:36.428393
Load end --2020-05-20T07:28:38.433409
💃
Load start --2020-05-20T07:28:38.433647
Load end --2020-05-20T07:28:40.436491
💄
Load start --2020-05-20T07:28:40.436734
Load end --2020-05-20T07:28:42.440696
💅
Load start --2020-05-20T07:28:42.441255
Load end --2020-05-20T07:28:44.445558
💆
Load start --2020-05-20T07:28:44.445801
Load end --2020-05-20T07:28:46.448190
💇
Load start --2020-05-20T07:28:46.448432
Load end --2020-05-20T07:28:48.452624
💈
Copy code
2.async*withyield*、await
Above
yield*Similarly,async*Use within the methodyield*The object must beStream<T>Object
getEmojiWithTimeCorrectfetchEmojisFlow MAP conversion, the front needs to be addedyield*
main() {
getEmojiWithTime(10).listen(print);
}
Stream<String> getEmojiWithTime(int count) async* {
yield* fetchEmojis(count).map((e) => '$e -- ${DateTime.now().toIso8601String()}');
}
Stream<String> fetchEmojis(int count) async*{
for (int i = 0; i < count; i++) {
yield await fetchEmoji(i);
}
}
Future<String> fetchEmoji(int count) async{
Runes first = Runes('\u{1f47f}');
await Future.delayed(Duration(seconds: 2));// Simulation time
return String.fromCharCodes(first.map((e) => e + count));
}
Copy code
👿 -- 2020-05-20T07:35:09.461624
💀 -- 2020-05-20T07:35:11.471223
💁 -- 2020-05-20T07:35:13.476712
💂 -- 2020-05-20T07:35:15.482848
💃 -- 2020-05-20T07:35:17.489429
💄 -- 2020-05-20T07:35:19.491214
💅 -- 2020-05-20T07:35:21.497086
💆 -- 2020-05-20T07:35:23.500867
💇 -- 2020-05-20T07:35:25.505379
💈 -- 2020-05-20T07:35:27.511723
Copy code
Four, Stream's use --streambuilder
Stream is the most commonly used in the component level
StreamBuilderThis article is just simple to use it, there will be a copyright in the future.StreamBuilderThe core of the component is to accept oneStream object,
Builder functionA different interface is constructed in different states of the stream element.
Top components
import 'dart:async';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(),
body: HomePage(),
));
}
}
Copy code
2. The use of theSTReambuilder components
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
Stream<String> _stream;
@override
void initState() {
super.initState();
_stream= fetchEmojis(10);
}
@override
Widget build(BuildContext context) {
return Center(
child: StreamBuilder<String>(
builder: _buildChildByStream,
stream: _stream,
),
);
}
Widget _buildChildByStream(
BuildContext context, AsyncSnapshot<String> snapshot) {
switch(snapshot.connectionState){
case ConnectionState.none:
break;
case ConnectionState.waiting:
return CircularProgressIndicator();
break;
case ConnectionState.active:
return Text(snapshot.requireData,style: TextStyle(fontSize: 60));
break;
case ConnectionState.done:
return Text('Stream Over--${snapshot.requireData}',style: TextStyle(fontSize: 30),);
break;
}
return Container();
}
Stream<String> fetchEmojis(int count) async* {
for (int i = 0; i < count; i++) {
yield await fetchEmoji(i);
}
}
Future<String> fetchEmoji(int count) async {
Runes first = Runes('\u{1f47f}');
AWAIT FUTURE.DELAYED (DURATION (Seconds: 1)); // Simulation time
return String.fromCharCodes(first.map((e) => e + count));
}
}
Copy code
Exterior:
If you have used it
flutter_blocWill useasync*Now I will see it again, is it clearer.
class CounterBloc extends Bloc<CounterEvent, int> {
@override
int get initialState => 0;
@override
Stream<int> mapEventToState(CounterEvent event) async* {
switch (event) {
case CounterEvent.decrement:
yield state - 1;
break;
case CounterEvent.increment:
yield state + 1;
break;
}
}
}
Copy code
end
welcomeStar and Folius FLUTTERUNIT Development, let us work together to become a Unit member.
In addition, I have a FLUTTER WeChat exchange group. Welcome to the small partner to share flutter's knowledge, look forward to communicating with you.
@ 2020.05.20 is not allowedMy public number: Programming KingContact me - E-mail: [email protected] - WeChat: zDL1994328~ END ~