Last active
August 25, 2024 08:27
-
-
Save iapicca/1e8d55e3e6f80f23d116df1e6d558d81 to your computer and use it in GitHub Desktop.
SharedPreferences web example
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/foundation.dart' show ValueListenable; | |
import 'package:shared_preferences/shared_preferences.dart' | |
show SharedPreferences; | |
import 'package:flutter/material.dart'; | |
void main() async { | |
final counter = await SharedCounter.instance(); | |
runApp( | |
MaterialApp( | |
home: Scaffold( | |
body: Center( | |
child: ValueListenableBuilder<int>( | |
valueListenable: counter, | |
builder: (context, count, _) => Text('$count'), | |
), | |
), | |
floatingActionButton: FloatingActionButton( | |
onPressed: () => counter.value++, | |
tooltip: 'Increment', | |
child: const Icon(Icons.add), | |
), | |
), | |
), | |
); | |
} | |
abstract class Counter extends ValueListenable<int> with ChangeNotifier { | |
@override | |
int get value; | |
set value(int value); | |
} | |
final class SharedCounter extends Counter { | |
SharedCounter._( | |
this._prefs, | |
String key, | |
this.initialValue, | |
) : _key = key; | |
final SharedPreferences _prefs; | |
final String _key; | |
final int initialValue; | |
static Future<SharedCounter> instance({ | |
String key = 'COUNTER', | |
initialValue = 0, | |
}) async => | |
SharedCounter._( | |
await SharedPreferences.getInstance(), | |
key, | |
initialValue, | |
); | |
@override | |
int get value => _prefs.getInt(_key) ?? initialValue; | |
@override | |
set value(int value) { | |
_prefs.setInt(_key, value); | |
notifyListeners(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment