Created
August 24, 2022 00:56
-
-
Save VB10/26b16bde2272aae778f554ddf19fb214 to your computer and use it in GitHub Desktop.
Cancelable Feature
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SamplePage extends StatefulWidget { | |
const SamplePage({Key? key}) : super(key: key); | |
@override | |
_SamplePageState createState() => _SamplePageState(); | |
} | |
class _SamplePageState extends State<SamplePage> { | |
void _fetchItems() { | |
_operation.value.then((value) { | |
_items = value ?? []; | |
setState(() {}); | |
}); | |
} | |
late CancelableOperation<List<UserModel>?> _operation; | |
List<UserModel> _items = []; | |
@override | |
void initState() { | |
super.initState(); | |
_operation = CancelableOperation.fromFuture( | |
SampleFutureCancel().fetchUsers(), | |
onCancel: () { | |
print('The request has been Canceled'); | |
}, | |
); | |
_fetchItems(); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar(leading: Text('${_items.length}')), | |
floatingActionButton: FloatingActionButton( | |
child: Text('Cancel Request'), | |
onPressed: () { | |
_operation.cancel(); | |
}, | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment