26
loading...
This website collects cookies to deliver better user experience
flutter pub add shared_preferences
in your terminal or simply add this statement to your pubspec.yaml file.dependencies:
shared_preferences: ^2.0.6
import 'package:shared_preferences/shared_preferences.dart';
SharedPreferences prefs = await SharedPreferences.getInstance();
await
keyword. This means that getting an instance of SharedPreferences is asynchronous and requires a little extra setup. You'll either need to use a FutureBuilder widget, or simply wrap it in an asynchronous function by using the async
keyword, like I've done here:void setUserNamePref() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
}
void setUserNamePref(String userName) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('userName', userName);
}
prefs.setString('userName', userName);
prefs.setString
.Future<String> getUserNamePref() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.getString('userName');
}
Future
and mark our function definition with async
. Future<String> getUserNamePref() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.getString('userName') ?? 'Carl';
}
'userName'
doesn't exist, we can instead return the String 'Carl' so that the program can proceed!