In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces "what are the methods for Flutter and Dart to cancel Future". In daily operation, I believe that many people have doubts about the methods of canceling Future by Flutter and Dart. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the questions of "what are the methods of Flutter and Dart to cancel Future?" Next, please follow the editor to study!
Use asynchronous packages (recommended)
The async package is developed and released by the authors of the Dart programming language. It provides dart:async-style utilities to enhance asynchronous computing. What can help us cancel Future is the CancelableOperation class:
Var myCancelableFuture = CancelableOperation.fromFuture (Future inner, {FutureOr onCancel ()}) / / call the cancel () method to cancel the futuremyCancelableFuture.cancel ()
For more clarity, see the actual example below.
Complete example
Apply Preview
The application we are building has a floating button. When this button is pressed, the asynchronous operation begins (this takes 5 seconds to complete). The background of the button has changed from indigo to red, its label has changed from "start" to "cancel", and you can now use it to cancel Future.
If you click the cancel button within 5 seconds before the Future is completed, the screen will display "Future has been cancelled".
If you do nothing, the screen will display "Future completed" after 5 seconds.
A demonstration is worth more than a thousand words:
Code
1. Install the asynchronous package by doing the following:
Flutter pub add async
Then run:
Flutter pub get
Complete source code in 2.main.dart (with explanation):
/ / main.dartimport 'package:flutter/material.dart';import' package:async/async.dart';void main () {runApp (const MyApp ());} class MyApp extends StatelessWidget {const MyApp ({Key? Key}): super (key: key); @ override Widget build (BuildContext context) {return MaterialApp (/ / Remove the debug banner debugShowCheckedModeBanner: false, title: 'Journey to the Big Front end', theme: ThemeData (primarySwatch: Colors.indigo,), home: const HomePage ());} class HomePage extends StatefulWidget {const HomePage ({Key? Key}): super (key: key); @ override _ HomePageState createState () = > _ HomePageState ();} class _ HomePageState extends State {/ / this future will return some text once it completes Future _ myFuture () async {await Future.delayed (const Duration (seconds: 5)); return 'Future completed';} / / keep a reference to CancelableOperation CancelableOperation? _ myCancelableFuture; / / This is the result returned by the future String? _ text; / / Help you know whether the app is "loading" or not bool _ isLoading = false / / This function is called when the "start" button is pressed void _ getData () async {setState (() {_ isLoading = true;}); _ myCancelableFuture = CancelableOperation.fromFuture (_ myFuture (), onCancel: () = > 'Future has been canceld',); final value = await _ myCancelableFuture?.value; / / update the UI setState (() {_ text = value; _ isLoading = false;}) } / / this function is called when the "cancel" button is tapped void _ cancelFuture () async {final result = await _ myCancelableFuture?.cancel (); setState (() {_ text = result; _ isLoading = false;});} @ override Widget build (BuildContext context) {return Scaffold (appBar: AppBar (title: const Text)), body: Center (child: _ isLoading? Const CircularProgressIndicator (): Text (_ text?? 'Press Start Button', style: const TextStyle (fontSize: 28), / / This button is used to trigger _ getDate () and _ cancelFuture () functions / / the function is called depends on the _ isLoading variable floatingActionButton: ElevatedButton (onPressed: () = > _ isLoading? _ cancelFuture (): _ getData (), child: Text (_ isLoading? 'Cancel':' Start'), style: ElevatedButton.styleFrom (padding: const EdgeInsets.symmetric (vertical: 20, horizontal: 30), primary: _ isLoading? Colors.red: Colors.indigo),),);}} use the timeout () method
This method is fast and simple. However, it is not very flexible.
Using the timeout () method, you can limit the time of the Future (for example, 3 seconds). If the future completes in time, its value will be returned. On the other hand, if the Future exceeds the limit time, the onTimeout function is executed:
Future timeout (Duration timeLimit, {FutureOr onTimeout ()?}) Quick example
Create a virtual Future:
Future _ myFuture () async {await Future.delayed (const Duration (seconds: 10)); return 'Future completed';}
Set a timeout of 3 seconds:
_ myFuture () .timeout (const Duration (seconds: 3), onTimeout: () = > 'The process took too much time to finish. Please try again later',); convert Future to stream
You can use the asStream () method of the Future class to create a stream that contains the original Future results. You can now unsubscribe from the stream.
Quick example / / don't forget to import thisimport 'dart:async';// Create a demo futureFuture _ loadData () async {await Future.delayed (const Duration (seconds: 10)); return' Some Data';} / / a reference to the stream subscription// so that we can call _ sub.cancel () laterStreamSubscription? _ sub;// convert the future to a stream_sub = _ loadData (). AsStream (). Listen ((data) {/ / do something with "data" print (data);}) / / cancel the stream subscription_sub.cancel ()
Note that this quick example only briefly describes how things work. You must modify it so that it can run in an existing project.
At this point, the study on "what are the methods for Flutter and Dart to cancel Future" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.