How to Use Shared Preferences to Stored Data in Flutter
Tags: flutter
Published: 2020-09-14 17:22:52

---
title: How to Use Shared Preferences to Stored Data in Flutter

published: true
date: 2020-08-13 12:37:24 UTC
tags: flutter
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/2aek09vdtoxlo75mxk0g.png
canonical_url: https://alltechsavvy.com/shared-preferences-flutter/
---



Shared preferences flutter is for Storing simple data on Device for Reading & writing Simple Key-value pairs in iOS & Android.

In Simple Example, Let Just Say You Just Want to Stored Simple Data on Phone And Later You can refer that Data whenever You Launch that App then Shared preferences will help you to Stored data on the Phone.

Shared preferences in flutter **NSUserDefaults** on iOS & macOS, and **SharedPreferences** on Android.

#### Shared Preferences Flutter in Android & iOS Watch Video:-

{% youtube TdlTXINB-ac %}


For this project, we are will Need **[Shared\_prefernces ](https://pub.dev/packages/shared_preferences)Package.**

**Let’s Start the Tutorial**

If you Don’t know how to Create a [Flutter app](https://dev.to/sagarshende/how-to-add-ads-to-flutter-app-in-under-10-min-4acn-temp-slug-8668684), check out [Getting started with Flutter](https://flutter.io/getting-started/) official tutorial.


**💻 Installation**


First, you will need to add the package name `shared_preferences `into Pubspec.yaml

In the `dependencies:` section of your `pubspec.yaml`, add the following lines as **Shared preferences:**

Now run  **Flutter package get** in your terminal which we’ll install `shared_preferences `package.

```
import 'package:flutter/material.dart';
import 'package:shared_preferences_flutter/main.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: !isFirstScreen ? IntroScreen() : HomeScreen(),
      
    );
  }
}
```

In Above Code We Create MyApp StatefulWidget And in the home properties we have isFirsScreen.

to Stored Boolean Value we Need to Create Variable isFirstScreen as Below:

```
  bool isFirstScreen = false;
```

As Set As False because the First time it’s going to show me Introduction Screen.

After that We Need to Create **Introduction Screen** & **Home Screen**

**Introduction Screen**

```
class IntroScreen extends StatefulWidget {
  @override
  _IntroScreenState createState() => _IntroScreenState();
}

class _IntroScreenState extends State<IntroScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text("Intro Screen"),
          RaisedButton(
            onPressed: () {},
            child: Text("GO to HomeScreen"),
          )
        ],
      ),
    ));
  }
}

```

In Above Intro Screen we Implement Text widget & Raised Button After that you need to add OnPressed Functionality To Navigate from Intro Screen to Home Screen For that Create **gotoHomeScreen()**

```
  void gotoHomeScreen(context) async {
    ///Shared Preferences wiill stored types String , int , bool, double
    SharedPreferences pref = await SharedPreferences.getInstance();
    await pref.setBool('seen', true);
    Navigator.of(context).pushReplacement(
      MaterialPageRoute(
        builder: (context) => HomeScreen(),
      ),
    );
  }
```

So in the above code, We Add Shared preferences get an instance of the & then using pref variable we are set bool value Key & Value As a **‘seen’ and true**

**Home Screen**

```
class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Text(
          "Home Screen",
          style: TextStyle(
            fontSize: 30,
          ),
        ),
      ),
    );
  }
}

```

And then We need to get That Key in MyApp for that We need to create checkFirstScreen in the MyApp Widget.

with help of getBool method we Getting An Key as **‘seen’**

```
  Future<void> checkFirstScreen() async {
    SharedPreferences pref = await SharedPreferences.getInstance();
    //if First statement is Null Or NO Value then it will give us Second Value
    bool seen = (pref.getBool('seen') ?? false);
    if (seen) {
      setState(() {
        isFirstScreen = true;
      });
    } else {
      setState(() {
        isFirstScreen = false;
      });
    }
  }

```

**Full Code:-**

```
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  bool isFirstScreen = false;

  @override
  void initState() {
    super.initState();
    checkFirstScreen();
  }

  Future<void> checkFirstScreen() async {
    SharedPreferences pref = await SharedPreferences.getInstance();
    //if First statement is Null Or NO Value is returning then it will give us Second Value
    bool seen = (pref.getBool('seen') ?? false);
    if (seen) {
      setState(() {
        isFirstScreen = true;
      });
    } else {
      setState(() {
        isFirstScreen = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: !isFirstScreen ? IntroScreen() : HomeScreen(),
    );
  }
}

class IntroScreen extends StatefulWidget {
  @override
  _IntroScreenState createState() => _IntroScreenState();
}

class _IntroScreenState extends State<IntroScreen> {
  void gotoHomeScreen(context) async {
    ///SHare String , int , bool, double
    SharedPreferences pref = await SharedPreferences.getInstance();
    await pref.setBool('seen', true);
    Navigator.of(context).pushReplacement(
      MaterialPageRoute(
        builder: (context) => HomeScreen(),
      ),
    );
  }
///Sagar shende
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text("Intro Screen"),
          RaisedButton(
            onPressed: () {
              gotoHomeScreen(context);
            },
            child: Text("GO to HomeScreen"),
          )
        ],
      ),
    ));
  }
}

class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Text(
          "Home Screen",
          style: TextStyle(
            fontSize: 30,
          ),
        ),
      ),
    );
  }
}

```

**You can see the full source code of the project ** [**here**](https://github.com/sagarshende23/shared_preference_flutter)**.**

[https://github.com/sagarshende23/shared_preference_flutter](https://i.imgur.com/BaG7hIp.jpg)


**🤝 Show Some Support**


 [![ksUVYCz.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1600105599143/xYL2Bsot3.png)](https://www.youtube.com/channel/UCEW4YMELtVeLjcpAzevNabg?sub_confirmation=1) 



If you liked the app, show some love Here⭐️ 


Enjoyed the Tutorial? Please leave a LIKE 👍 to show your support and appreciation 


💬 If you have a question about anything in the video, leave me a comment and I’ll do my best to answer it.


original post **[here](https://alltechsavvy.com/shared-preferences-flutter/)**