当前位置:网站首页>[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 )
边栏推荐
- awk从入门到入土(1)awk初次会面
- GBase 8c系统表-pg_am
- 【教程】chrome關閉跨域策略cors、samesite,跨域帶上cookie
- random shuffle注意
- Restcloud ETL cross database data aggregation operation
- Apple releases MacOS 11.6.4 update: mainly security fixes
- Random Shuffle attention
- 【翻译】后台项目加入了CNCF孵化器
- cvpr2022去雨去雾
- [fluent] listview list (map method description of list set | vertical list | horizontal list | code example)
猜你喜欢

Build a private cloud disk cloudrev
![[shutter] setup of shutter development environment (supplement the latest information | the latest installation tutorial on August 25, 2021)](/img/65/c1fe95f8c391394f7ff1b75c7d75b6.jpg)
[shutter] setup of shutter development environment (supplement the latest information | the latest installation tutorial on August 25, 2021)

"Analysis of 43 cases of MATLAB neural network": Chapter 43 efficient programming skills of neural network -- Discussion Based on the characteristics of the new version of MATLAB r2012b

通达OA v12流程中心

Principle and application of database

How to change the panet layer in yolov5 to bifpn

where 1=1 是什么意思

怎么将yolov5中的PANet层改为BiFPN

Random shuffle note

The use of Flink CDC mongodb and the implementation of Flink SQL parsing complex nested JSON data in monggo
随机推荐
Unrecognized SSL message, plaintext connection?
GBase 8c系统表pg_database
Job object of collaboration in kotlin
GBase 8c系统表-pg_constraint
GBase 8c系统表-pg_aggregate
Gbase 8C function / stored procedure definition
Return a tree structure data
【翻译】后台项目加入了CNCF孵化器
8 free, HD, copyright free video material download websites are recommended
The use of Flink CDC mongodb and the implementation of Flink SQL parsing complex nested JSON data in monggo
How to change the panet layer in yolov5 to bifpn
Tongda OA V12 process center
Thread safe singleton mode
Random Shuffle attention
错误Invalid bound statement (not found): com.ruoyi.stock.mapper.StockDetailMapper.xxxx解决
SPI机制
Apple releases MacOS 11.6.4 update: mainly security fixes
[translation] flux is safe. Gain more confidence through fuzzy processing
MUX VLAN Foundation
Detailed introduction to the usage of Nacos configuration center