Skip to content

Instantly share code, notes, and snippets.

@VB10
Created August 24, 2022 00:56
Show Gist options
  • Save VB10/26b16bde2272aae778f554ddf19fb214 to your computer and use it in GitHub Desktop.
Save VB10/26b16bde2272aae778f554ddf19fb214 to your computer and use it in GitHub Desktop.
Cancelable Feature
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