Flutter: Local Storage (Shared Preferences) — Auto Login
Welcome to another part of my Flutter tutorials. As I am on a journey in exploring more about Flutter, I will be penning down useful mechanisms that we may use in the daily mobile apps we build.
Today, I will be touching on a popular topic call Local Storage, which will use a shared_preferences package to help us achieve what we want.
In very simple words, local storage helps us to store data that can be reused at a later time even after the app is shut down. One very simple use case is when we want to auto-login a user.
So let’s get started by creating a new project with flutter create auto_login
.
Add shared_preferences: ^0.5.1+2
into pubspec.yaml
file and run flutter packages get
.
You can replace the code in main.dart
with this:
- Firstly we import
shared_preferences.
- In
initState
we callautoLogin
to render the correct UI. - We have
loginUser
andlogout
to store and delete ourusername
.