Skip to content

Instantly share code, notes, and snippets.

@iapicca
Last active August 25, 2024 08:27
Show Gist options
  • Save iapicca/1e8d55e3e6f80f23d116df1e6d558d81 to your computer and use it in GitHub Desktop.
Save iapicca/1e8d55e3e6f80f23d116df1e6d558d81 to your computer and use it in GitHub Desktop.
SharedPreferences web example
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