xxxxxxxxxx
//write this in terminal to add the package
flutter pub add shared_preferences
import 'package:shared_preferences/shared_preferences.dart';
xxxxxxxxxx
add this line to terminal to get the newest version
flutter pub add shared_preferences
xxxxxxxxxx
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
TextEditingController _textEditingController = TextEditingController();
void _saveToPreferences() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('myKey', _textEditingController.text);
}
void _loadFromPreferences() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
String? myText = prefs.getString('myKey');
setState(() {
_textEditingController.text = myText ?? '';
});
}
@override
void initState() {
super.initState();
_loadFromPreferences();
}
@override
void dispose() {
_textEditingController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Shared Preferences Example'),
),
body: Center(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: TextFormField(
controller: _textEditingController,
onChanged: (value) => _saveToPreferences(),
decoration: InputDecoration(
labelText: 'Enter some text',
),
),
),
),
);
}
}
xxxxxxxxxx
// Obtain shared preferences.
final prefs = await SharedPreferences.getInstance();
// Save an integer value to 'counter' key.
await prefs.setInt('counter', 10);
// Save an boolean value to 'repeat' key.
await prefs.setBool('repeat', true);
// Save an double value to 'decimal' key.
await prefs.setDouble('decimal', 1.5);
// Save an String value to 'action' key.
await prefs.setString('action', 'Start');
// Save an list of strings to 'items' key.
await prefs.setStringList('items', <String>['Earth', 'Moon', 'Sun']);
//READ DATA
// Try reading data from the 'counter' key. If it doesn't exist, returns null.
final int? counter = prefs.getInt('counter');
// Try reading data from the 'repeat' key. If it doesn't exist, returns null.
final bool? repeat = prefs.getBool('repeat');
// Try reading data from the 'decimal' key. If it doesn't exist, returns null.
final double? decimal = prefs.getDouble('decimal');
// Try reading data from the 'action' key. If it doesn't exist, returns null.
final String? action = prefs.getString('action');
// Try reading data from the 'items' key. If it doesn't exist, returns null.
final List<String>? items = prefs.getStringList('items');