Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/// Use SharedPreferences in Flutter effortlessly
/// https://medium.com/@simonpham/use-sharedpreferences-in-flutter-effortlessly-835bba8f7418
// utils/shared_prefs.dart
class SharedPrefs {
static SharedPreferences _sharedPrefs;
init() async {
if (_sharedPrefs == null) {
_sharedPrefs = await SharedPreferences.getInstance();
}
}
String get username => _sharedPrefs.getString(keyUsername) ?? "";
set username(String value) {
_sharedPrefs.setString(keyUsername, value);
}
}
final sharedPrefs = SharedPrefs();
// constants/strings.dart
const String keyUsername = "key_username";
// main.dart
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await sharedPrefs.init();
runApp(
MyApp(),
);
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Text("Hi ${sharedPrefs.username}"),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.