How to install and use shared_preferences with Flutter 3.10.2 - including code sample!
A popular Flutter package with 7418 likes that support Flutter version 3.10.2 and above. Last version of the package was published on May 31, 2023.Installing shared_preferences
You can either add the package directly using the flutter command line.
In either case, make sure to refresh your packages by running the following command:
$ flutter pub add shared_preferences
dependencies:
shared_preferences: ^2.1.1
In either case, make sure to refresh your packages by running the following command:
$ flutter pub get
Using shared_preferences
Once you have installed the package, you can use it in your Flutter application by importing it.
import 'package:shared_preferences/shared_preferences.dart';
How to use shared_preferences with a code example/sample
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: public_member_api_docs
import 'dart:async';
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(BuildContext context) {
return const MaterialApp(
title: 'SharedPreferences Demo',
home: SharedPreferencesDemo(),
);
}
}
class SharedPreferencesDemo extends StatefulWidget {
const SharedPreferencesDemo({super.key});
@override
SharedPreferencesDemoState createState() => SharedPreferencesDemoState();
}
class SharedPreferencesDemoState extends State {
final Future _prefs = SharedPreferences.getInstance();
late Future _counter;
Future _incrementCounter() async {
final SharedPreferences prefs = await _prefs;
final int counter = (prefs.getInt('counter') ?? 0) + 1;
setState(() {
_counter = prefs.setInt('counter', counter).then((bool success) {
return counter;
});
});
}
@override
void initState() {
super.initState();
_counter = _prefs.then((SharedPreferences prefs) {
return prefs.getInt('counter') ?? 0;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('SharedPreferences Demo'),
),
body: Center(
child: FutureBuilder(
future: _counter,
builder: (BuildContext context, AsyncSnapshot snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
case ConnectionState.waiting:
return const CircularProgressIndicator();
case ConnectionState.active:
case ConnectionState.done:
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
return Text(
'Button tapped ${snapshot.data} time${snapshot.data == 1 ? '' : 's'}.\n\n'
'This should persist across restarts.',
);
}
}
})),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}