How to show updated list in shared preferences on UI - Flutter - flutter

I am making an app in a flutter in which I can select the contacts from phone book and saving them in shared preferences. No problem in data saving and retrieving but i m struggling with showing the updated list on my UI. It is showing the contacts list but every time I click on Load button it duplicates the list and showing 2 lists , 1 previous and other updated .
how can i show just updated list on UI ?
here is my code:
import 'package:contacts_test/select_contacts.dart';
import 'package:contacts_test/shared_pref.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';
import 'contact_model.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Flutter Demo',
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
SharedPref sharedPref = SharedPref();
ContactModel modelLoad = ContactModel(displayName: 'saniya' , phoneNumber: '324235 ');
List _list = [];
#override
initState() {
super.initState();
// Add listeners to this clas
// loadSharedPrefs();
}
loadSharedPrefs() async {
try {
print('in load shared pref-- getting keys ');
final prefs = await SharedPreferences.getInstance();
final keys = prefs.getKeys();
print('now load shared pref ');
for (String key in keys) {
ContactModel user = ContactModel.fromJson(await sharedPref.read(key));
_list.add(user);
}
print('done load shared pref ');
}
catch (Excepetion) {
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("contacts "),
),
body: Builder(
builder: (context) {
return Column(children: [
RaisedButton(
onPressed: () {
Navigator.push(
context, MaterialPageRoute(builder: (context) => Plugin1()));
},
child: const Text('fluttercontactpicker - plugin1'),
),
RaisedButton(
onPressed: () async {
await loadSharedPrefs();
},
child: Text('Load', style: TextStyle(fontSize: 20)),
),
Expanded(
child: _list.isNotEmpty ?
ListView.builder(
shrinkWrap: true,
itemCount: _list.length,
itemBuilder: (context, position) {
return ListTile(
leading: Icon(Icons.contacts),
title: Text(
_list[position].displayName.toString()
),
trailing: Icon(Icons.delete));
},
) : Center(child: Text('No list items to show')),
),
]);
}
),
);
}
}

Your loadSharedPrefs(); function adds each contact to the list you show. Every time you press the button, the same elements are added again to the list. There are multiple ways to avoid that. You can: empty the list before filling it, you can write a for loop to loop over the length of the incoming contacts and for each to add it to the list by always starting from index 0. In case you use some kind of replacement or removing method, make sure you call setState(()=> { });

Base on the answer, here is a possible solution:
import 'package:contacts_test/select_contacts.dart';
import 'package:contacts_test/shared_pref.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';
import 'contact_model.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Flutter Demo',
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
SharedPref sharedPref = SharedPref();
ContactModel modelLoad = ContactModel(displayName: 'saniya' , phoneNumber: '324235 ');
List _list = [];
#override
initState() {
super.initState();
// Add listeners to this clas
// loadSharedPrefs();
}
loadSharedPrefs() async {
try {
print('in load shared pref-- getting keys ');
final prefs = await SharedPreferences.getInstance();
final keys = prefs.getKeys();
print('now load shared pref ');
var newList = [];
for (String key in keys) {
ContactModel user = ContactModel.fromJson(await sharedPref.read(key));
newList.add(user);
}
setState(()=> { _list = newList; });
print('done load shared pref ');
}
catch (Excepetion) {
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("contacts "),
),
body: Builder(
builder: (context) {
return Column(children: [
RaisedButton(
onPressed: () {
Navigator.push(
context, MaterialPageRoute(builder: (context) => Plugin1()));
},
child: const Text('fluttercontactpicker - plugin1'),
),
RaisedButton(
onPressed: () async {
await loadSharedPrefs();
},
child: Text('Load', style: TextStyle(fontSize: 20)),
),
Expanded(
child: _list.isNotEmpty ?
ListView.builder(
shrinkWrap: true,
itemCount: _list.length,
itemBuilder: (context, position) {
return ListTile(
leading: Icon(Icons.contacts),
title: Text(
_list[position].displayName.toString()
),
trailing: Icon(Icons.delete));
},
) : Center(child: Text('No list items to show')),
),
]);
}
),
);
}
}

Related

Flutter App with provider and persistent storage

I have been trying to figure out how to build an app in flutter with persistant state manager. I can't seem to get it to work. This is my app with a state manager.
I want to store actual classes, and not just an integer, which makes this a bit tricker, but hey, that's my goal.
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() {
runApp(
/// Use a provider. Multiprovider works just fine
MultiProvider(
providers: [
ChangeNotifierProvider(create: (_) => State()),
],
child: const MyApp(),
),
);
}
// Define the data type we want to use
// We will use time and value to track data over time
class MyData {
final DateTime time;
final int value;
MyData(this.time, this.value);
}
// Use a state with a change notifier (provider stuff)
class State with ChangeNotifier {
late List<MyData> _dataset = [];
List<MyData> get dataset => _dataset;
State() {
// The dataset is a list of objects
_dataset = [];
}
void addData(time, value) {
// Add data to the dataset
MyData datapoint = MyData(time, value);
_dataset.add(datapoint);
}
void clearData() {
// Clear the dataset
_dataset = [];
}
}
// The actual widget
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return const MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
const MyHomePage({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Example'),
),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text('You have added this many datapoints'),
const Count(),
IconButton(
onPressed: () =>
context.read<State>().addData(DateTime.now(), 100),
icon: const Icon(Icons.add)),
IconButton(
onPressed: () => context.read<State>().clearData(),
icon: const Icon(Icons.remove))
],
),
),
);
}
}
// And the parsing of the data to a widget
class Count extends StatelessWidget {
const Count({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Text(
/// Calls `context.watch` to make [Count] rebuild when [Counter] changes.
'${context.watch<State>().dataset.length}',
key: const Key('counterState'),
style: Theme.of(context).textTheme.headlineMedium,
);
}
}
The question is. How can I add a persistent logic to this?
The persistent data can be added in the initialization of the state. In order to save the data in a Key-value storage, each object needs to be stringified using something like json.encode and json.decode.
Here's an updated code snippet that will work.
I removed your comment, and added comments wherever I added code that will add the persistence logic.
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
// Add shared_preferences and convert
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';
void main() {
runApp(
MultiProvider(
providers: [
ChangeNotifierProvider(create: (_) => State()),
],
child: const MyApp(),
),
);
}
class MyData {
final DateTime time;
final int value;
MyData(this.time, this.value);
// Add a converter to from JSON
static MyData fromJSON(Map<String, dynamic> jsonData) {
return MyData(DateTime.fromMillisecondsSinceEpoch(jsonData["time"]),
jsonData["value"]);
}
// Add a converter to from an encoded JSON string
static MyData fromJSONString(String jsonDataString) {
Map<String, dynamic> jsonData = json.decode(jsonDataString);
return MyData.fromJSON(jsonData);
}
// Add a converter to JSON
dynamic toJSON() {
return {"time": time.millisecondsSinceEpoch, "value": value};
}
// Add a converter to JSON string
String toJSONString() {
return json.encode(toJSON());
}
}
class State with ChangeNotifier {
late List<MyData> _dataset = [];
List<MyData> get dataset => _dataset;
State() {
_dataset = [];
// Read the data on the creation of a state
readData();
}
void readData() async {
// Load the data from the shared preferences
final prefs = await SharedPreferences.getInstance();
List<String>? datasetStrings = prefs.getStringList("dataset");
datasetStrings ??= [];
// Load the data into the state
_dataset = datasetStrings
.map((jsonData) => MyData.fromJSONString(jsonData))
.toList();
// Notify the listeners
notifyListeners();
}
void setData() async {
// Load the shared preferences
final prefs = await SharedPreferences.getInstance();
// Load the data into the shared preferences
List<String> datasetStrings =
_dataset.map((dataPoint) => dataPoint.toJSONString()).toList();
await prefs.setStringList("dataset", datasetStrings);
}
void addData(time, value) {
MyData dataPoint = MyData(time, value);
_dataset.add(dataPoint);
// Save the data and notify listeners
setData();
notifyListeners();
}
void clearData() {
_dataset = [];
setData();
notifyListeners();
}
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return const MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
const MyHomePage({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Example'),
),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text('You have pushed the button this many times:'),
const Count(),
IconButton(
onPressed: () =>
context.read<State>().addData(DateTime.now(), 100),
icon: const Icon(Icons.add)),
IconButton(
onPressed: () => context.read<State>().clearData(),
icon: const Icon(Icons.remove)),
// Also add a refresh button to test
// loading of data without losing debugging connection
IconButton(
onPressed: () => context.read<State>().readData(),
icon: const Icon(Icons.refresh))
],
),
),
);
}
}
class Count extends StatelessWidget {
const Count({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Text(
/// Calls `context.watch` to make [Count] rebuild when [Counter] changes.
'${context.watch<State>().dataset.length}',
key: const Key('counterState'),
style: Theme.of(context).textTheme.headlineMedium,
);
}
}

How Update the data shown in one page after changing the data in database from the second page

In my Home page I am fetching data from Firestore database and showing them using a ListView.builder. More specifically, I am showing all the subjects that belongs to the current user. In home page there is a button which takes us the FirstPage where users can create new subject. When user create a subject, that subject is added to the database. But when user go back to the Home page, data shown there should be updated, i,e. the list of subjects shown there should contain the newly created subject.
I am using streamController to call setState in Home page after the new subject is added to database but it is not working i,e. when user go back to home page it shows the previous data only. All other things are working (i,e. data is successfully added to data base. When I again reload the home page it shows updated data)
Can someone look into it and tell me what's wrong with my approach ? Or if it is possible with the provider package, then can you please give me an example of that in similar situation.
Here is my code,
// Stream controller
StreamController<bool> streamControllerHome = StreamController<bool>();
Future main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
runApp(MyApp());
}
class MyApp extends StatefulWidget {
MyApp({Key? key}) : super(key: key);
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.deepPurple
),
home: Home(stream: streamControllerHome.stream),
);
}
}
// Code for Home page
class Home extends StatefulWidget {
final Stream<bool> stream;
const Home({Key? key, required this.stream}) : super(key: key);
#override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
setStateHome(bool check) {
if (check) {
setState(() {
});
}
}
#override
void initState() {
// TODO: implement initState
super.initState();
if (!streamControllerHome.hasListener) {
widget.stream.listen((event) {
setStateHome(event);
});
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Home'),
),
body: FutureBuilder(
future: FirebaseFirestore.instance.collection('users').doc(FirebaseAuth.instance.currentUser!.uid).get(),
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
case ConnectionState.waiting:
case ConnectionState.active:
return const Center(child: CircularProgressIndicator(),);
case ConnectionState.done:
if (snapshot.hasError) {
return const Center(child: Text('Error'));
}
if (!snapshot.hasData) {
return const Center(child: Text('No Data'),);
}
Map<String, dynamic> data = snapshot.data as Map<String, dynamic>;
List<String> subjects = data['subjects'];
return ListView.builder(
itemCount: subjects.length,
itemBuilder: (context, index) {
return Column(
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: [
const Icon(Icons.book),
const SizedBox(width: 10,),
Text(subjects[index]),
],
),
)
],
);
},
);
}
}
),
floatingActionButton: FloatingActionButton(
onPressed: () {
Navigator.push(context, MaterialPageRoute(builder: (context) {
return const FirstPage();
}));
},
),
);
}
}
// Code for FirstPage
class FirstPage extends StatefulWidget {
const FirstPage({Key? key}) : super(key: key);
#override
State<FirstPage> createState() => _FirstPageState();
}
class _FirstPageState extends State<FirstPage> {
final textController = TextEditingController();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('FirstPage'),
),
body: Column(
children: [
TextField(
controller: textController,
decoration: const InputDecoration(
labelText: 'Subject Name',
hintText: 'Type the subject here',
),
),
TextButton(
onPressed: () async {
await FirebaseFirestore.instance.collection('users').doc(FirebaseAuth.instance.currentUser!.uid)
.update({'subjects' : FieldValue.arrayUnion([textController.text])});
streamControllerHome.add(true);
},
child: const Text('Create Subject')
)
],
)
);
}
}
This is broken:
future: FirebaseFirestore.instance.collection('users').doc(FirebaseAuth.instance.currentUser!.uid).get(),
for reasons given in the first few paragraphs of FutureBuilder documentation, and illustrated in my oft-referenced video https://www.youtube.com/watch?v=sqE-J8YJnpg.
In brief, you cannot build a future as the future: parameter of a FutureBuilder. You need to lift it out into State.

Instantiating a List with Provider

I am trying to learn how to use ChangeNotifierProvider and have gotten stuck. I've setup the class as so:
void main() => runApp(
ChangeNotifierProvider(create: (context) => ItemList(),
child: MyApp(),
)
);
class ItemData {
final String title;
final int score;
ItemData({required this.title, required this.score});
}
class ItemList extends ChangeNotifier{
final _items = [];
void add(item){
_items.add(item);
notifyListeners();
}
void update(){
notifyListeners();
}
}
final itemList = ItemList();
Now I want to create the list:
I'm trying to add items by calling:
itemList.add(ItemData({elements}))
but this isn't working. How do I create my list so I can put it into a Listview Builder?
Try this one:
main.dart
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() => runApp(
const MyApp(),
);
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: ChangeNotifierProvider(
create: (context) => ItemList(), child: const NewHomePage()),
);
}
}
class NewHomePage extends StatefulWidget {
const NewHomePage({Key? key}) : super(key: key);
#override
_NewHomePageState createState() => _NewHomePageState();
}
class _NewHomePageState extends State<NewHomePage> {
#override
Widget build(BuildContext context) {
return Consumer<ItemList>(builder: (context, providerItem, child) {
return Scaffold(
appBar: AppBar(
backgroundColor: const Color(0XFF2e3438),
),
body: Column(
mainAxisSize: MainAxisSize.min,
children: [
providerItem.basketItem.isEmpty
? const Text("No item in the list")
: ListView.builder(
itemCount: providerItem.basketItem.length,
shrinkWrap: true,
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
"Title: " + providerItem.basketItem[index].title),
);
}),
ElevatedButton(
onPressed: () {
providerItem.addItem(ItemData(
title: DateTime.now().toString(),
score: DateTime.now().month));
print("data added successfully" +
providerItem.basketItem.length.toString());
},
child: const Text("Add Data")),
],
));
});
}
}
item_data.dart
class ItemData {
final String title;
final int score;
ItemData({required this.title, required this.score});
}
item_list.dart
class ItemList extends ChangeNotifier {
List<ItemData> _items = [];
void addItem(ItemData itemData) {
_items.add(itemData);
notifyListeners();
}
List<ItemData> get basketItem {
return _items;
}
}

Flutter: Error when displaying single list value

In Flutter I am reading a file from disk and displaying the list items as a list. Using ListView.builder works fine but with a text widget displaying a single value I get this error. Can someone help?
The error I get is The following RangeError was thrown building MyHomePage(dirty, state: _MyHomePageState#e9932):
RangeError (index): Invalid value: Valid value range is empty: 9
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:flutter/services.dart';
import 'dart:async';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
//This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(),
);
}
}
______________________________
WITH List.View.builder
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List<String> _names = [];
Future<List<String>> loadNames() async {
List<String> names = [];
await rootBundle.loadString('assets/Stulkur_A.txt').then((q) => {
for (String i in LineSplitter().convert(q)) {names.add(i)}
});
return names;
}
_setup() async {
List<String> names = await loadNames();
setState(() {
_names = names;
});
}
#override
void initState() {
_setup();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Names'),
),
body: Center(
child: Container(
padding: EdgeInsets.all(15),
child: ListView.builder(
itemCount: _names.length,
itemBuilder: (context, index) {
return Text(_names[index]);
})),
),
);
}
}
_____________________
WITH Text widget
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List<String> _names = [];
Future<List<String>> loadNames() async {
List<String> names = [];
await rootBundle.loadString('assets/Stulkur_A.txt').then((q) => {
for (String i in LineSplitter().convert(q)) {names.add(i)}
});
return names;
}
_setup() async {
List<String> names = await loadNames();
setState(() {
_names = names;
});
}
#override
void initState() {
_setup();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Names'),
),
body: Center(
child: Container(
padding: EdgeInsets.all(15),
child: Text(_names[9]),
),
),
);
}
}
Try
body: Center(
child: Container(
padding: EdgeInsets.all(15),
child: _names.isEmpty
? CircularProgressIndicator()
: ListView.builder(
itemCount: _names.length,
itemBuilder: (context, index) {
return Text(_names[index]);
},
),
),
),
You should check if _names.length == 0 show a loader or everything you want otherwise show the ListView widget.

What is the proper way of using SharedPreferences with Provider in Flutter?

I am newbie to state management using provider in flutter.
I've created a model named as Counter:
import 'package:flutter/foundation.dart';
class Counter with ChangeNotifier {
int value = 0;
void increment() {
value++;
notifyListeners();
}
void decrement() {
value--;
notifyListeners();
}
}
Now when value changes I can save it locally using SharedPreferences in order to start from that value next time.
But, I do not know what would be a proper way of loading data from local and set value in Counter class.
Should I load saved data in main.dart file when app is initalized and then setValue to that data?
Or are there any solutions, for example, loading data directly in my Counter class?
create a SharedPreferencesProvider
import 'package:shared_preferences/shared_preferences.dart';
class SharedPreferencesProvider {
final Future<SharedPreferences> sharedPreferences;
SharedPreferencesProvider(this.sharedPreferences);
Stream<SharedPreferences> get prefsState => sharedPreferences.asStream();
}
then create a Provider and with a StreamProvider as shown below
return MultiProvider(
providers: [
Provider<SharedPreferencesProvider>(create: (_) => SharedPreferencesProvider(SharedPreferences.getInstance())),
StreamProvider(create: (context) => context.read<SharedPreferencesProvider>().prefsState, initialData: null)
then consume the state within a Widget build with a context.watch
#override
Widget build(BuildContext context) {
sharedPrefs = context.watch<SharedPreferences>();
Try to use the future builder and then set it to the provider and be able to use SharedPreferences everywhere in the app:
#override
Widget build(BuildContext context) {
return FutureBuilder<SharedPreferences>(
future: SharedPreferences.getInstance(),
builder: (context, snapshot) {
if (snapshot.hasData && snapshot.data != null) {
return MultiProvider(providers: [
Provider<SharedPreferences>(
create: (context) => snapshot.data!,
),
],
);
}
},
);
}
And you can use context.read() everywhere.
The question is leaning toward opinion. I'm also new to flutter -- the below may not be the best way, but it does work, so maybe it will help someone.
If it's the top level app, you can initialize the counter before actually using it, displaying a loading page during the load time (imperceptible in this case). You must include the first runApp however, otherwise shared_preferences will not be able to correctly access the file containing these preferences on the device.
A similar thing can be done with with FutureBuilder, but you must await a delay prior to attempting to read from shared_preferences.
(I don't think the loading page or delay are necessary if you aren't using the widget as your top level widget, which would probably be better anyway. In that case, probably FutureBuilder would be the correct solution. (?))
To note:
I added an async "constructor" to the Counter class that initializes from the shared_preferences.
I access the Counter via provider library in _MyHomePageState.build with context.watch<Counter>(), which causes this to rebuild on changes (without requiring calls to setState.
I've added async Counter._updatePreferences which is called in Counter.increment and Counter.decrement, which saves the current value of the Counter to the shared_preferences.
Imports and main for first method
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
Future<void> main() async {
// run "loading" app while awaiting counter, then run app again
runApp(
const MaterialApp(
home: Center(
child: Text('Loading'),
),
)
);
final Counter counter = await Counter.fromPreferences();
runApp(
ChangeNotifierProvider<Counter>.value(
value: counter,
child: const MyApp(),
)
);
}
Imports and main (with FutureBuilder)
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
// Get counter in future builder
runApp(
FutureBuilder<Counter>(
future: Counter.fromPreferences(),
builder: (BuildContext context, AsyncSnapshot<Counter> snapshot) {
Widget returnWidget = const MaterialApp(
home: Center(
child: Text('Loading'),
),
);
if (snapshot.connectionState == ConnectionState.waiting) {
} else if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasError) {
print(snapshot.error);
} else if (snapshot.hasData) {
final Counter counter = snapshot.data!;
returnWidget = ChangeNotifierProvider<Counter>.value(
value: counter,
child: const MyApp(),
);
} else {
print('No data');
}
} else if (snapshot.connectionState == ConnectionState.none) {
print('null future');
} else {
print(snapshot.connectionState);
}
return returnWidget;
},
),
);
}
MyApp and MyHomePage
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Counter App',
home: MyHomePage(title: 'Counter App Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
final Counter counter = context.watch<Counter>();
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You have pushed the button this many times:',
),
Text(
'${counter.value}',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: <FloatingActionButton>[
FloatingActionButton(
onPressed: counter.increment,
child: const Icon(Icons.add),
),
FloatingActionButton(
onPressed: counter.decrement,
child: const Icon(Icons.remove),
),
],
),
);
}
}
Counter Class (ChangeNotifier)
class Counter extends ChangeNotifier {
int value = 0;
static Future<Counter> fromPreferences() async {
final Counter counter = Counter();
// Must be included if using the FutureBuilder
// await Future<void>.delayed(Duration.zero, () {});
final SharedPreferences prefs = await SharedPreferences.getInstance();
final int value = prefs.getInt('counterValue') ?? 0;
counter.value = value;
return counter;
}
Future<void> _updatePreferences() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setInt('counterValue', value);
}
void increment() {
value++;
notifyListeners();
_updatePreferences();
}
void decrement() {
value--;
notifyListeners();
_updatePreferences();
}
}
Complete Example
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
Future<void> main() async {
// run "loading" app while awaiting counter, then run app again
runApp(
const MaterialApp(
home: Center(
child: Text('Loading'),
),
)
);
final Counter counter = await Counter.fromPreferences();
runApp(
ChangeNotifierProvider<Counter>.value(
value: counter,
child: const MyApp(),
)
);
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Counter App',
home: MyHomePage(title: 'Counter App Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
final Counter counter = context.watch<Counter>();
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You have pushed the button this many times:',
),
Text(
'${counter.value}',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: <FloatingActionButton>[
FloatingActionButton(
onPressed: counter.increment,
child: const Icon(Icons.add),
),
FloatingActionButton(
onPressed: counter.decrement,
child: const Icon(Icons.remove),
),
],
),
);
}
}
class Counter extends ChangeNotifier {
int value = 0;
static Future<Counter> fromPreferences() async {
final Counter counter = Counter();
// Must be included if using the FutureBuilder
// await Future<void>.delayed(Duration.zero, () {});
final SharedPreferences prefs = await SharedPreferences.getInstance();
final int value = prefs.getInt('counterValue') ?? 0;
counter.value = value;
return counter;
}
Future<void> _updatePreferences() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setInt('counterValue', value);
}
void increment() {
value++;
notifyListeners();
_updatePreferences();
}
void decrement() {
value--;
notifyListeners();
_updatePreferences();
}
}
Use the shared_preferences plugin
enter link description here
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'SharedPreferences Demo',
home: SharedPreferencesDemo(),
);
}
}
class SharedPreferencesDemo extends StatefulWidget {
SharedPreferencesDemo({Key key}) : super(key: key);
#override
SharedPreferencesDemoState createState() => SharedPreferencesDemoState();
}
class SharedPreferencesDemoState extends State<SharedPreferencesDemo> {
Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
Future<int> _counter;
Future<void> _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<int>(
future: _counter,
builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return const CircularProgressIndicator();
default:
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),
),
);
}
}
Reference site : https://pub.dev/packages/shared_preferences#-example-tab-