Last active
January 9, 2023 10:05
-
-
Save wingkit-leung/6a533709cb5f29e834da521f8abf9576 to your computer and use it in GitHub Desktop.
Flutter cross platform data persistence solution: shared_preferences with riverpod
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'; | |
import 'package:shared_preferences/shared_preferences.dart'; | |
// A Counter example implemented with riverpod and shared_preferences | |
/// Providers are declared globally and specify how to create a state | |
final counterProvider = StateProvider((ref) => 0); | |
final sharedPrefs = Provider<SharedPreferences>((ref) { | |
throw UnimplementedError(); | |
}); | |
Future<void> main() async { | |
WidgetsFlutterBinding.ensureInitialized(); | |
final sharedPreferences = await SharedPreferences.getInstance(); | |
runApp( | |
// Adding ProviderScope enables Riverpod for the entire project | |
ProviderScope(overrides: [ | |
sharedPrefs.overrideWithValue(sharedPreferences), | |
], child: const MyApp()), | |
); | |
} | |
class MyApp extends StatelessWidget { | |
const MyApp({Key? key}) : super(key: key); | |
@override | |
Widget build(BuildContext context) { | |
return const MaterialApp(home: Home()); | |
} | |
} | |
class Home extends ConsumerWidget { | |
const Home({Key? key}) : super(key: key); | |
@override | |
Widget build(BuildContext context, WidgetRef ref) { | |
return Scaffold( | |
appBar: AppBar(title: const Text('Flutter101')), | |
body: Center( | |
child: Consumer(builder: (context, ref, _) { | |
final count = ref.watch(counterProvider.state).state; | |
final prefs = ref.read(sharedPrefs); | |
final countPref = prefs.getInt('counter') ?? 0; | |
if (count != countPref) { | |
Future.delayed(Duration.zero).then( | |
(value) => ref.read(counterProvider.state).state = countPref); | |
} | |
return Text( | |
'$countPref', | |
style: | |
DefaultTextStyle.of(context).style.apply(fontSizeFactor: 5.0), | |
); | |
}), | |
), | |
floatingActionButton: FloatingActionButton( | |
onPressed: () { | |
final prefs = ref.read(sharedPrefs); | |
final countPref = (prefs.getInt('counter') ?? 0) + 1; | |
prefs.setInt('counter', countPref); | |
ref.read(counterProvider.state).state = countPref; | |
}, | |
child: const Icon(Icons.add), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment