Skip to content

Instantly share code, notes, and snippets.

@iapicca
Created May 24, 2024 09:29
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';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({
super.key,
required this.title,
});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
late final Counter counter;
@override
Widget build(context) => FutureBuilder<Counter>(
future: SharedCounter.instance(),
builder: (context, counter) {
return switch (counter.connectionState) {
ConnectionState.done => Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ValueListenableBuilder<int>(
valueListenable: counter.data!,
builder: (context, count, _) => Text(
'$count',
style: Theme.of(context).textTheme.headlineMedium,
),
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () => counter.data!.value++,
tooltip: 'Increment',
child: const Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
),
_ => const CircularProgressIndicator(),
};
});
}
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) : _key = key;
final SharedPreferences _prefs;
final String _key;
static Future<SharedCounter> instance({String key = 'COUNTER'}) async =>
SharedCounter._(await SharedPreferences.getInstance(), key);
@override
int get value => _prefs.getInt(_key) ?? 0;
@override
set value(int value) {
_prefs.setInt(_key, value);
notifyListeners();
}
}
name: issue_149023
description: ''
publish_to: 'none'
version: 1.0.0+1
environment:
sdk: '>=3.4.1 <4.0.0'
dependencies:
flutter:
sdk: flutter
shared_preferences: ^2.2.3
dev_dependencies:
flutter_lints: ^3.0.0
flutter:
uses-material-design: true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment