set and get
- Flutter course
- Intermediate
- Lesson 38/99
- 4 min
Learn setString, getInt and getString methods.
set and get methods
To write data with shared_preferences, you use setString, setInt, setBool, setDouble methods. To read, you call getString, getInt, getBool methods. Set methods return Future<bool>, get methods return the value (or null).
await prefs.setString('name', 'Ada'); // write
await prefs.setInt('age', 25); // write
prefs.getString('name'); // 'Ada'
prefs.getInt('age'); // 25Get methods and null
If the key hasn't been written before, get methods return null. You can provide a default value with the ?? operator: prefs.getString('theme') ?? 'light'. This way the default theme is used on first launch.
final theme = prefs.getString('theme') ?? 'light';
final count = prefs.getInt('count') ?? 0;Practice Write with setInt, read with getInt
Get prefs with getInstance, write a value with setInt('count', 7), read it with getInt('count'), and print it.
Starter code
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
final prefs = await SharedPreferences.getInstance();
// setInt ile 'count' = 7 yaz
// getInt ile oku ve print ile bastır
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(home: Scaffold(body: Center(child: Text('set ve get')));
}
}Sample solution
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
final prefs = await SharedPreferences.getInstance();
await prefs.setInt('count', 7);
print(prefs.getInt('count'));
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(home: Scaffold(body: Center(child: Text('set ve get')));
}
}Expected output
7
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which method is used to read a stored int value?
- getString
- setInt
- setString
- getInt Correct answer
Explanation: To read an int value, use getInt; setInt is for writing, and getString reads a String.
2 Write a value with setInt
await prefs.____;
await prefs.setInt('count', 7);
Explanation: Use setInt to store an int; it takes a key and an int value. setString takes a String, and getInt reads.
3 Method - type matching
| Term | Meaning |
|---|---|
setString |
Writes a String |
getString |
Reads a String |
setInt |
Writes an int |
getInt |
Reads an int |