当前位置:网站首页>[fluent] future asynchronous programming (introduction | then method | exception capture | async, await keywords | whencomplete method | timeout method)
[fluent] future asynchronous programming (introduction | then method | exception capture | async, await keywords | whencomplete method | timeout method)
2022-07-03 02:32:00 【Programmer community】
List of articles
- One 、Future brief introduction
- Two 、Future.then Use
- 3、 ... and 、Future Exception trapping
- Four 、Dart Practice site
- 5、 ... and 、async、await keyword
- 6、 ... and 、whenComplete Method
- 7、 ... and 、timeout Method
- 8、 ... and 、 Related resources
One 、Future brief introduction
Future Refer to future Of Some time Of result , Can be a value , It can also be an error message ;
With the help of Future Asynchronous operation can be realized ;
Future Is in dart:async The class in the package , The system will import the classes in this package by default , It can be used directly , No need to import deliberately ;
Future There are two states :
- ① In execution , Pending state ;
- ② Execution results , Complete state ;
Two 、Future.then Use
call then Method , In this way , obtain Future The value in , The type is Future Types in generics ;
call testFuture After the method , call then Method , Can get testFuture Method String character string , Namely s Parameters , Print the string ;
Future<String> testFuture() {
return Future.value('success');}main() {
testFuture().then((s) {
print(s); });}
Future Of then The prototype of the method is as follows :
/// Register callbacks to be called when this future completes. /// /// When this future completes with a value, /// the [onValue] callback will be called with that value. /// If this future is already completed, the callback will not be called /// immediately, but will be scheduled in a later microtask. /// /// If [onError] is provided, and this future completes with an error, /// the `onError` callback is called with that error and its stack trace. /// The `onError` callback must accept either one argument or two arguments /// where the latter is a [StackTrace]. /// If `onError` accepts two arguments, /// it is called with both the error and the stack trace, /// otherwise it is called with just the error object. /// The `onError` callback must return a value or future that can be used /// to complete the returned future, so it must be something assignable to /// `FutureOr<R>`. /// /// Returns a new [Future] /// which is completed with the result of the call to `onValue` /// (if this future completes with a value) /// or to `onError` (if this future completes with an error). /// /// If the invoked callback throws, /// the returned future is completed with the thrown error /// and a stack trace for the error. /// In the case of `onError`, /// if the exception thrown is `identical` to the error argument to `onError`, /// the throw is considered a rethrow, /// and the original stack trace is used instead. /// /// If the callback returns a [Future], /// the future returned by `then` will be completed with /// the same result as the future returned by the callback. /// /// If [onError] is not given, and this future completes with an error, /// the error is forwarded directly to the returned future. /// /// In most cases, it is more readable to use [catchError] separately, /// possibly with a `test` parameter, /// instead of handling both value and error in a single [then] call. /// /// Note that futures don't delay reporting of errors until listeners are /// added. If the first `then` or `catchError` call happens /// after this future has completed with an error, /// then the error is reported as unhandled error. /// See the description on [Future]. Future<R> then<R>(FutureOr<R> onValue(T value), {
Function? onError});
then The first parameter of the method FutureOr<R> onValue(T value)
Namely Future Of onValue Value represented , The type is Future The generic type R ;
then The second argument to the method {Function? onError}
It's optional , Methods for catching exceptions ;
3、 ... and 、Future Exception trapping
Mode one : then Methods the incoming onError Parameters ;
In execution The return value is Future Type of testFuture When the method is used , stay then In the method , The second parameter onError
Future<String> testFuture() {
return Future.value('success');}main() {
testFuture().then((s) {
print(s); }, onError: (e) {
print('onError:'); print(e); });}
Mode two : Continue the chain call , stay then After the method , Continue to call Future Of catchError Method ;
Future<String> testFuture() {
return Future.value('success');}main() {
testFuture().then((s) {
print(s); }).catchError((e) {
print('catchError:'); print(e); });}
Be careful : Only one of the above two methods can be selected , If it's all set , Then only Mode one take effect , Mode two Will be covered ;
Four 、Dart Practice site
stay https://dartpad.dartlang.org/ Website , practice Dart Language ;
5、 ... and 、async、await keyword
async Keywords are generally used as Method suffix , Modified method The return value must be Future Type of ;
Method execution , With In the form of synchronization Execute to await Keyword location , then Hang up , Wait for the subsequent asynchronous method execution ;
After the asynchronous task is executed , await Then the code starts to execute ;
6、 ... and 、whenComplete Method
stay Future At the end of the execution , If you want to perform some tasks , It can be called in a chain , call Future Of whenComplete Method ;
This method is similar to try … catch … finally Medium finally Code block , Is the code that must be executed , Even if the accident is wrong , The code will also be executed ;
Future<String> testFuture() {
return Future.value('success');}main() {
testFuture().then((s) {
print(s); }).catchError((e) {
print('catchError:'); print(e); }).whenComplete(() {
print('whenComplete'); });}
7、 ... and 、timeout Method
Some asynchronous operations may take a long time to complete , Here you specify a timeout for asynchronous operations ;
stay Future Chain call , call timeout Method , Set timeout ;
void main() {
/// There will be delays in asynchronous operations 3 second , Timeout time 2 second new Future.delayed(new Duration(seconds: 3), () {
return 1; }).timeout(new Duration(seconds: 2)).then(print).catchError(print);}
8、 ... and 、 Related resources
Reference material :
- Flutter Official website : https://flutter.dev/
- Flutter Plug in download address : https://pub.dev/packages
- Flutter Developing documents : https://flutter.cn/docs ( Strongly recommend )
- official GitHub Address : https://github.com/flutter
- Flutter The Chinese community : https://flutter.cn/
- Flutter Practical tutorial : https://flutter.cn/docs/cookbook
- Flutter CodeLab : https://codelabs.flutter-io.cn/
- Dart Chinese document : https://dart.cn/
- Dart Developer website : https://api.dart.dev/
- Flutter Chinese net : https://flutterchina.club/ , http://flutter.axuer.com/docs/
- Flutter Related issues : https://flutterchina.club/faq/ ( It is recommended to watch it at the introductory stage )
- GitHub Upper Flutter Open source examples : https://download.csdn.net/download/han1202012/15989510
- Flutter Practical e-books : https://book.flutterchina.club/chapter1/
Important topics :
- Flutter Animation reference documentation : https://flutterchina.club/animations/
Blog source download :
GitHub Address : https://github.com/han1202012/flutter_http( Keep updating with the progress of the blog , There may not be the source code of this blog )
Blog source snapshot : https://download.csdn.net/download/han1202012/21528472 ( The source code snapshot of this blog , You can find the source code of this blog )
边栏推荐
- [Hcia]No.15 Vlan间通信
- Gbase 8C system table PG_ aggregate
- Restcloud ETL cross database data aggregation operation
- SPI机制
- Memory pool (understand the process of new developing space from the perspective of kernel)
- GBase 8c 函数/存储过程参数(一)
- Oauth2.0 authentication, login and access "/oauth/token", how to get the value of request header authorization (basictoken)???
- GBase 8c系统表-pg_constraint
- Mathematical statistics -- Sampling and sampling distribution
- Linear rectification function relu and its variants in deep learning activation function
猜你喜欢
Principle and application of database
The use of Flink CDC mongodb and the implementation of Flink SQL parsing complex nested JSON data in monggo
SPI mechanism
Linear rectification function relu and its variants in deep learning activation function
《MATLAB 神经网络43个案例分析》:第43章 神经网络高效编程技巧——基于MATLAB R2012b新版本特性的探讨
random shuffle注意
Distributed transaction solution
8 free, HD, copyright free video material download websites are recommended
How to change the panet layer in yolov5 to bifpn
The Linux server needs to install the agent software EPS (agent) database
随机推荐
GBase 8c触发器(三)
Gbase 8C function / stored procedure parameters (II)
Awk from getting started to being buried (2) understand the built-in variables and the use of variables in awk
[shutter] setup of shutter development environment (supplement the latest information | the latest installation tutorial on August 25, 2021)
random shuffle注意
Gbase 8C function / stored procedure definition
GBase 8c 创建用户/角色 示例二
Gbase 8C system table PG_ amop
Summary of interview project technology stack
Gbase 8C system table PG_ attribute
[Flutter] dart: class;abstract class;factory;类、抽象类、工厂构造函数
基于线程池的生产者消费者模型(含阻塞队列)
Compréhension simple de SVG
Wechat - developed by wechat official account Net core access
GBase 8c系统表-pg_conversion
Interview stereotyped version
Gbase 8C system table PG_ collation
GBase 8c 函数/存储过程参数(二)
COM and cn
How to change the panet layer in yolov5 to bifpn