Created
April 18, 2023 10:30
-
-
Save anvuive456/912a13ba7ef68c90715c337e8a7637e1 to your computer and use it in GitHub Desktop.
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
| import 'package:flutter/material.dart'; | |
| import 'package:flutter_riverpod/flutter_riverpod.dart'; | |
| const Color darkBlue = Color.fromARGB(255, 18, 32, 47); | |
| class CountController extends StateNotifier<AsyncValue<int>> { | |
| CountController() : super(const AsyncData<int>(0)); | |
| Future<void> up() async { | |
| //because of it's loading | |
| // state = const AsyncLoading<int>(); | |
| state = await AsyncValue.guard<int>(() async { | |
| print(state.value); | |
| ///value is null?? | |
| final current = state.value ?? 0; | |
| return current + 1; | |
| }); | |
| // state = AsyncValue.data((state.value ?? 0 )+ 1); | |
| } | |
| } | |
| final countProvider = | |
| StateNotifierProvider.autoDispose<CountController, AsyncValue<int>>((ref) { | |
| return CountController(); | |
| }); | |
| void main() { | |
| runApp(ProviderScope(child: MyApp())); | |
| } | |
| class MyApp extends StatelessWidget { | |
| @override | |
| Widget build(BuildContext context) { | |
| return MaterialApp( | |
| theme: ThemeData.dark().copyWith( | |
| scaffoldBackgroundColor: darkBlue, | |
| ), | |
| debugShowCheckedModeBanner: false, | |
| home: Scaffold( | |
| body: Center( | |
| child: MyWidget(), | |
| ), | |
| ), | |
| ); | |
| } | |
| } | |
| class MyWidget extends ConsumerWidget { | |
| @override | |
| Widget build(BuildContext context, WidgetRef ref) { | |
| var count = ref.watch(countProvider); | |
| return Column( | |
| children: [ | |
| Text( | |
| 'Count: ${count.value}', | |
| style: Theme.of(context).textTheme.headline4, | |
| ), | |
| ElevatedButton( | |
| onPressed: () => ref.read(countProvider.notifier).up(), | |
| style: ElevatedButton.styleFrom( | |
| shape: const StadiumBorder(), | |
| ), | |
| child: const Text('up'), | |
| ) | |
| ], | |
| ); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment