var myCancelableFuture = CancelableOperation.fromFuture( Future<T> inner, { FutureOr onCancel()? } ) // call the cancel() method to cancel the future myCancelableFuture.cancel();为了更清楚,请参阅下面的实际示例。
flutter pub add async然后运行:
flutter pub get2.main.dart 中的完整源代码(附解释):
// main.dart import '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: '大前端之旅', 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<HomePage> { // this future will return some text once it completes Future<String?> _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), ), ); } }使用 timeout() 方法
Future<T> timeout( Duration timeLimit, {FutureOr<T> onTimeout()?} )快速示例
Future<String?> _myFuture() async { await Future.delayed(const Duration(seconds: 10)); return 'Future completed'; }2.设置超时 3 秒:
_myFuture().timeout( const Duration(seconds: 3), onTimeout: () => 'The process took too much time to finish. Please try again later', );3.将Future转换为流
// don't forget to import this import 'dart:async'; // Create a demo future Future<dynamic> _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() later StreamSubscription<dynamic>? _sub; // convert the future to a stream _sub = _loadData().asStream().listen((data) { // do something with "data" print(data); }); // cancel the stream subscription _sub.cancel();
请注意,这个快速示例仅简要描述了事物的工作原理。您必须对其进行修改以使其可在现有项目中运行。