Created
December 22, 2022 06:18
-
-
Save tank777/dc79f31db114176dce90aead4616eabc 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)); | |
Future<void> up() async { | |
state = const AsyncLoading<int>(); | |
state = await AsyncValue.guard<int>(() async { | |
return 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) { | |
final count = ref.watch(countProvider).value.toString(); | |
return SafeArea( | |
child: Column( | |
children: [ | |
Text( | |
'Count: $count', | |
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