Last active
December 1, 2022 11:02
-
-
Save hamza39460/04a529edb324bbbcbbe04f9f5b46c561 to your computer and use it in GitHub Desktop.
This file contains 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)) { | |
state = const AsyncLoading<int>(); | |
} | |
Future<void> up() async { | |
state = await AsyncValue.guard<int>(() async { | |
final current = state.value ?? 0; | |
return current + 1; | |
}); | |
} | |
} | |
final countProvider = | |
StateNotifierProvider<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) { | |
final count = ref.watch(countProvider); | |
return Column( | |
children: [ | |
Text( | |
'Count: $count', | |
style: Theme.of(context).textTheme.headline4, | |
), | |
ElevatedButton( | |
onPressed: () => ref.watch(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