preference_flutter 0.1.2
preference_flutter: ^0.1.2 copied to clipboard
Durable local-first storage for native Dart and Flutter apps.
example/lib/main.dart
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:preference_flutter/preference_flutter.dart';
void main() {
runApp(const PreferenceExampleApp());
}
/// A small native Flutter app using Preference for durable app state.
class PreferenceExampleApp extends StatelessWidget {
const PreferenceExampleApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Preference Example',
debugShowCheckedModeBanner: false,
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: const Color(0xff6750a4)),
useMaterial3: true,
),
home: const PreferenceHomePage(),
);
}
}
/// Demonstrates opening a store and persisting a simple value across launches.
class PreferenceHomePage extends StatefulWidget {
const PreferenceHomePage({super.key});
@override
State<PreferenceHomePage> createState() => _PreferenceHomePageState();
}
class _PreferenceHomePageState extends State<PreferenceHomePage> {
Preference? _database;
int _launchCount = 0;
Object? _error;
@override
void initState() {
super.initState();
_openDatabase();
}
Future<void> _openDatabase() async {
try {
final database = await Preference.open(
'${Directory.systemTemp.path}/preference_flutter_example.pref',
appId: 'com.example.preference_flutter',
databaseId: 'preference_flutter_example',
);
final previousCount = await database.get<int>('app/launchCount') ?? 0;
final nextCount = previousCount + 1;
await database.set<int>('app/launchCount', nextCount);
if (!mounted) return;
setState(() {
_database = database;
_launchCount = nextCount;
});
} catch (error) {
if (!mounted) return;
setState(() => _error = error);
}
}
Future<void> _reset() async {
final database = _database;
if (database == null) return;
await database.set<int>('app/launchCount', 0);
if (mounted) setState(() => _launchCount = 0);
}
@override
void dispose() {
_database?.close();
super.dispose();
}
@override
Widget build(BuildContext context) {
final error = _error;
return Scaffold(
appBar: AppBar(title: const Text('Preference Example')),
body: Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: error != null
? Text('Could not open the store: $error')
: _database == null
? const CircularProgressIndicator()
: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(Icons.storage_rounded, size: 56),
const SizedBox(height: 20),
const Text('Durable app state',
style: TextStyle(fontSize: 24)),
const SizedBox(height: 8),
Text('This app has opened $_launchCount times.'),
const SizedBox(height: 20),
FilledButton.tonalIcon(
onPressed: _reset,
icon: const Icon(Icons.restart_alt),
label: const Text('Reset counter'),
),
],
),
),
),
);
}
}