getInstance
- Flutter course
- Intermediate
- Lesson 37/99
- 4 min
Access asynchronously with SharedPreferences.getInstance.
What is getInstance?
To access the SharedPreferences class, you call the static getInstance() method. It returns a Future<SharedPreferences> because it reads from disk. Therefore you need to wait for it with await.
final prefs = await SharedPreferences.getInstance();
// now you can set/get through prefsasync main and ensureInitialized
When using shared_preferences in the main function, make main async and call WidgetsFlutterBinding.ensureInitialized() first. This ensures the Flutter binding is ready; otherwise you get an error in async main.
void main() async {
WidgetsFlutterBinding.ensureInitialized();
final prefs = await SharedPreferences.getInstance();
runApp(MyApp());
}Practice Call getInstance in async main
Make main async, call WidgetsFlutterBinding.ensureInitialized(), get the instance with await getInstance(), and print 'instance ready'.
Starter code
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
// ensureInitialized ve getInstance çağır
// 'instance ready' yazdır
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(home: Scaffold(body: Center(child: Text('getInstance')));
}
}Sample solution
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
final prefs = await SharedPreferences.getInstance();
print('instance ready');
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(home: Scaffold(body: Center(child: Text('getInstance')));
}
}Expected output
instance ready
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Why is getInstance async?
- Because it draws UI
- Because it compiles code
- Because it reads from disk Correct answer
- Because it downloads from the internet
Explanation: getInstance prepares the SharedPreferences instance by reading from disk; this takes time, so it returns a Future.
2 Await getInstance
final prefs = ____ SharedPreferences.getInstance();
final prefs = await SharedPreferences.getInstance();
Explanation: getInstance returns a Future; you use await to get its result.
3 getInstance parts
| Term | Meaning |
|---|---|
getInstance |
Returns a SharedPreferences instance |
await |
Waits for the Future result |
async |
Marks the function as async |
Future |
Represents the async result |