CodeBlanks Logo Icon CodeBlanks

getInstance

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 prefs

async 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

main.dart
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

main.dart
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

Question
final prefs = ____ SharedPreferences.getInstance();
Answer
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

All lessons in Intermediate