当前位置:网站首页>[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)
- Apple releases MacOS 11.6.4 update: mainly security fixes
- Servlet中数据传到JSP页面使用el表达式${}无法显示问题
- Wechat - developed by wechat official account Net core access
- [Flutter] dart: class;abstract class;factory;类、抽象类、工厂构造函数
- 《MATLAB 神经网络43个案例分析》:第43章 神经网络高效编程技巧——基于MATLAB R2012b新版本特性的探讨
- where 1=1 是什么意思
- 【教程】chrome關閉跨域策略cors、samesite,跨域帶上cookie
- Gbase 8C system table PG_ aggregate
- Tongda OA homepage portal workbench
猜你喜欢
![[shutter] banner carousel component (shutter_wiper plug-in | swiper component)](/img/a6/5c97ef3f34702b83ebf0511501d757.gif)
[shutter] banner carousel component (shutter_wiper plug-in | swiper component)

The data in servlet is transferred to JSP page, and the problem cannot be displayed using El expression ${}

xiaodi-笔记

Pytorch convolution network regularization dropblock

RestCloud ETL 跨库数据聚合运算

Basic operation of binary tree (C language version)

怎么将yolov5中的PANet层改为BiFPN

HTB-Devel

What does "where 1=1" mean

搭建私有云盘 cloudreve
随机推荐
Gbase 8C system table PG_ cast
[Flutter] dart: class; abstract class; factory; Class, abstract class, factory constructor
Why choose a frame? What frame to choose
二维格式数组格式索引下标连续问题导致 返回json 格式问题
[advanced ROS] Lesson 6 recording and playback in ROS (rosbag)
JS的装箱和拆箱
Gbase 8C system table PG_ authid
SQL statement
[shutter] setup of shutter development environment (supplement the latest information | the latest installation tutorial on August 25, 2021)
Awk from entry to burial (1) awk first meeting
为什么会选择框架?选择什么样的框架
Gbase 8C system table PG_ class
Build a private cloud disk cloudrev
Detailed introduction to the usage of Nacos configuration center
Servlet中数据传到JSP页面使用el表达式${}无法显示问题
GBase 8c系统表pg_cast
簡單理解svg
QT qcombobox add qccheckbox (drop-down list box insert check box, including source code + comments)
Simple understanding of SVG
COM和CN