当前位置:网站首页>[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 )
边栏推荐
- [advanced ROS] Lesson 6 recording and playback in ROS (rosbag)
- Javescript 0.1 + 0.2 = = 0.3 problem
- GBase 8c 创建用户/角色 示例二
- 怎么将yolov5中的PANet层改为BiFPN
- SPI mechanism
- Gbase 8C system table PG_ attribute
- [tutorial] chrome turns off cross domain policies CORS and samesite, and brings cookies across domains
- MATLAB小技巧(24)RBF,GRNN,PNN-神经网络
- Gbase 8C function / stored procedure parameters (II)
- [Hcia]No.15 Vlan间通信
猜你喜欢

Awk from introduction to earth (0) overview of awk

Memory pool (understand the process of new developing space from the perspective of kernel)
![[shutter] banner carousel component (shutter_wiper plug-in | swiper component)](/img/a6/5c97ef3f34702b83ebf0511501d757.gif)
[shutter] banner carousel component (shutter_wiper plug-in | swiper component)
【ROS进阶篇】第六讲 ROS中的录制与回放(rosbag)

Classes and objects - initialization and cleanup of objects - constructor call rules

Producer consumer model based on thread pool (including blocking queue)

Tongda OA V12 process center

Build a private cloud disk cloudrev

4. Classes and objects

8 free, HD, copyright free video material download websites are recommended
随机推荐
通达OA 首页门户工作台
awk从入门到入土(2)认识awk内置变量和变量的使用
怎么将yolov5中的PANet层改为BiFPN
Unrecognized SSL message, plaintext connection?
oauth2.0鉴权,登录访问 “/oauth/token”,请求头Authorization(basicToken)如何取值???
Startup mode and scope builder of collaboration in kotlin
GBase 8c系统表-pg_amop
搭建私有云盘 cloudreve
[shutter] bottom navigation bar page frame (bottomnavigationbar bottom navigation bar | pageview sliding page | bottom navigation and sliding page associated operation)
Choose it when you decide
Tongda OA homepage portal workbench
GBase 8c系统表-pg_class
[shutter] setup of shutter development environment (supplement the latest information | the latest installation tutorial on August 25, 2021)
【Flutter】shared_ Preferences local storage (introduction | install the shared_preferences plug-in | use the shared_preferences process)
Mathematical statistics -- Sampling and sampling distribution
GBase 8c 函数/存储过程参数(二)
The data in servlet is transferred to JSP page, and the problem cannot be displayed using El expression ${}
Gbase 8C system table PG_ authid
Detailed introduction to the deployment and usage of the Nacos registry
Gbase 8C system table PG_ amop