[-Flutter / dart syntax -】 Sync * and Async *, Yield and Yield *, Async and Await

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 syntaxKeywordIt 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, usegetEmojiWithTime yield*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 syntaxKeywordIt 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*withyieldawait

async*Is a DART syntaxKeywordIt 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

Aboveyield*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 levelStreamBuilderThis 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 itflutter_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 allowed
My public number: Programming King
Contact me - E-mail: [email protected] - WeChat: zDL1994328
~ END ~

Intelligent Recommendation

Generator (Asynchronous Programming, Yield, Next (), AWAIT, ASYNC)

Tip: Generator is an iterator generating function, which is an iterator that can be used for asynchronous calls. iterator protocol: Define a standard way to generate a limited or unlimited sequence va...

Use of Async AWAIT in ES6 (replacing generator yield)

Async AWAIT and Generator Yield are basically the same, but the use of Async AWAIT is more concise, and no need to write runner () to perform the code of each part, and the official is already availab...

Detailed Python coroutine: from yield/send to yield from to async/await

The history of coroutine development in Python is divided into three phases: Initial generator deformation yield/send Introducing @asyncio.coroutine and yield from Introducing the async/await keyword ...

Python-recovery - from yield/send to yield from to async/await

The coroutines in Python probably go through the following three phases: Initial generator deformation yield/send Introducing @asyncio.coroutine and yield from Introduced the async/await keyword in th...

Understanding Python coroutines: from yield/send to yield from to async/await

Coroutines in Python have probably gone through the following three stages: 1. The original generator deformation yield/send 2. Introduce @asyncio.coroutine and yield from 3. Introduce the async/await...

More Recommendation

Research on synchronization of async and yield

One, async, await usage Results of the: Two, * function, yield and next() usage Results of the:...

python3 async await yield from asynchronous programming understanding

Coroutine evolution The evolution of a few key words yield yield from asyncio.coroutine, async await future is to be understood that the words To understand the difference between iterators generator ...

Thoroughly understand Nodejs in Callback, Promise, Yield, Async, Await

Callback is the most classic writing in nodejs Because readfiles are asynchronous, it is futile to return Return in Function. You must receive callbacks with CB (Callback's shorthand), but this will i...

Future, await, and async in Dart

Future, await, and async in Dart General: After observing the code phenomenon, I finally understood the relationship between these three things. The method returns a Future indicating that the method ...

Future and async/await in dart

in conclusion Asynchronous function: The function marked with the aync keyword, its return value is a normalized Future object, such a function is called an asynchronous function There are two waystra...

Copyright  DMCA © 2018-2026 - All Rights Reserved - www.programmersought.com  User Notice

Top