Flutter SharedPreferences Example: The Simplest Way to store data in Flutter App with Example

Flutter SharedPreferences Example
Flutter SharedPreferences Example

Flutter SharedPreferences Example: You may be wondering why I am saying the most superficial way because storing the data is not an easy task for any beginner developer. Still, when you finish reading this post, you will be able to understand how to save data to your flutter app on android and IOS. 

This will be very simple because we will use a plugin for storing the data you don’t have to code too much. Shared Preference is the plugin that will do our work for storing data in the form of key-value pairs.

Let’s start (Flutter SharedPreferences Example)

Step1: Creating the flutter project

First, you need to create a flutter project for this use this command 

flutter create project_name

Step2: Adding the dependencies (SharedPreferences)

Now go to your pubspec.yaml file and add package shared_preference plugin this is the package that flutter provides us for getting access to the app storage and we will use this for storing data and getting data updating and deleting data. You can add these lines to pubspec.yaml file.

dependencies:
  flutter:
    sdk: flutter
  shared_preferences: ^2.0.15

Or you can do it by command line terminal just paste this command.

flutter pub add shared_preferences

This will add the shred_preference package to your pubspec.yaml file and later we can use it inside our app.

Step3: Editing the main.dart file

Make a file shared_preference_example.dart we will use this as our home page so we have to change our projects main.dart file so for that go to your main.dart file and delete everything because we will make this app from scratch. copy and paste this code to your main.dart.

import 'package:flutter/material.dart';
import 'package:multiselectdrop/shared_preference_example.dart';
 
void main() {
  runApp(const MyApp());
}
 
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
 
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const SharePreferenceExample(),
    );
  }
}

Step4: Creating the home page

  1. Next step is to create a home page for our app for this create a new file and name it shared_preference_example.dart inside your lib folder. inside this file make a stateful widget and name it SharedPreferenceExample and call this class from main.dart file because we have made it our home page.

The code for this file is as follows

import 'package:flutter/material.dart';
 
class SharePreferenceExample extends StatefulWidget {
  const SharePreferenceExample({Key? key}) : super(key: key);
 
  @override
  State<SharePreferenceExample> createState() => _SharePreferenceExampleState();
}
 
class _SharePreferenceExampleState extends State<SharePreferenceExample> {
  TextEditingController controller = TextEditingController();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Shared Preference'),
      ),
      body: body(controller),
    );
  }
 
  body() {
    return Container();
  }
}

As you can see for the body of the scaffold I have created a separate method body we will be working inside this body you have to pass the text editing controller here.

The code for the body widget is as follows.

body(TextEditingController controller) {
    return Container(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Padding(
            padding: EdgeInsets.symmetric(horizontal: 20),
            child: TextField(
		
              decoration: InputDecoration(
                hintText: 'Enter you name',
              ),
            ),
          ),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
            child: ElevatedButton(
              onPressed: saveToPhone(controller.text),
              child: const Text('Save to phone Storage'),
            ),
          ),
        ],
      ),
    );

Our body widget is returning a Container and we took a column for the child for this container for the children we took a text field and a button to perform actions on shared preference now your app should look like this.

For taking the input value from textfield we have to define a TextEditingController type variable. Like I have defined.

Step5: Storing the data

Now the actual fun part begins: create a method named saveToPhone and assign it to buttons onPressed property. Import the shared preference package

import 'package:shared_preferences/shared_preferences.dart';

Now inside your saveToPhone function create an instance of shared preference.

SharedPreferences preferences = await SharedPreferences.getInstance();

This saveToPhone method will receive a String as an argument and we will save this string to phone storage. We have a text input field in our app in which you can enter any string and when we press the button this function will get the value with the help of the text editing controller as I wrote in code.

Once we have the string value then we call setString function that is written in SharedPreference class it will return a bool value. If the value is saved without any error it returns true and if there is any error it returns false. The setString method saves the value in key-value pair so we need to define the key for storing the value like in the below code 

saveToPhone(String name) async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    try {
      preferences.setString('name', name);
    } catch (e) {
      print(e.toString());
    }
  }

You can save different values like integer, bool, double. 

The methods are setInt, setDouble, setBool.

SharedPreferences preferences = await   SharedPreferences.getInstance();
preferences.setInt(‘integer value’, 123);
preferences.setBool('bool value', false);
preferences.setDouble('double value', 12.2);

Step6: Getting the data

Now you know how to save different values to phone storage. Next, we will take a look at how we can get the values from storage. For reading the data from storage we need only the key that we used when we saved the data like we gave the “name” key in our example.

The shared preference class has methods to read data. We can use these methods. Now here is the function code to get data from storage.

getFromPhone() async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    try {
      return preferences.getString('name');
    } catch (e) {
      print(e.toString());
    }
  }

Once you have the data you can use it anywhere in your app. The best example to use shared preferences is storing the log-in detail like user name, email, etc. if you have these data in your phone storage then you can use this data to identify the user or auto login the user.

The other method for getting the data are.

SharedPreferences preferences = await   SharedPreferences.getInstance();
preferences.getInt(‘integer value’);
preferences.getBool('bool value',);
preferences.getDouble('double value');

Step7: Full code

The full code for the app is as follow

Filename – main.dart

import 'package:flutter/material.dart';
import 'package:multiselectdrop/shared_preference_example.dart';
 
void main() {
  runApp(MyApp());
}
 
class MyApp extends StatelessWidget {
  MyApp({Key? key}) : super(key: key);
 
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const SharePreferenceExample(),
    );
  }
}

Filename – shared_preference_example.dart

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
 
class SharePreferenceExample extends StatefulWidget {
  const SharePreferenceExample({Key? key}) : super(key: key);
 
  @override
  State<SharePreferenceExample> createState() => _SharePreferenceExampleState();
}
 
class _SharePreferenceExampleState extends State<SharePreferenceExample> {
  TextEditingController controller = TextEditingController();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Shared Preference'),
      ),
      body: body(controller),
    );
  }
 
  body(TextEditingController controller) {
    return Container(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 20),
            child: TextField(
              controller: controller,
              decoration: const InputDecoration(
                hintText: 'Enter you name',
              ),
            ),
          ),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
            child: ElevatedButton(
              onPressed: saveToPhone(controller.text),
              child: const Text('Save to phone Storage'),
            ),
          ),
        ],
      ),
    );
  }
 
  saveToPhone(String name) async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    try {
      preferences.setString('name', name);
    } catch (e) {
      print(e.toString());
    }
  }
 
  getFromPhone() async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    try {
      return preferences.getString('name');
 
    } catch (e) {
      print(e.toString());
    }
  }
}

shared_preferences  Plugin (LINK).


For more Flutter tutorials, Tips, Tricks, Free code, Questions, and Error Solving.

Remember FlutterDecode.com

2 thoughts on “Flutter SharedPreferences Example: The Simplest Way to store data in Flutter App with Example”

Leave a Comment