본문 바로가기
Dart (Flutter)

[Flutter] Save Data using Shared Preferences

by llHoYall 2022. 4. 1.

Flutter provides SharedPreferences class that supports saving data to a shared preference file as key-value pair.

Prerequisite

If you want to use this feature on iOS, it needs cocoapods.

Please find the materials on the official site.

https://guides.cocoapods.org/using/getting-started.html#installation

 

If you are using homebrew, you can simply install it.

$ brew install cocoapods

Register Packages

We need shared_preferences packages.

Let's add it into pubspec.yaml file.

# pubspec.yaml

...
dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2
  shared_preferences: 2.0.13
...

You can find the latest version on this link.

https://pub.dev/packages/shared_preferences

How to Use SharedPreferences Package

This is the most important part of this post.

 

import 'package:shared_preferences/shared_preferences.dart';

First, import the package.

 

If you want to save data, use the form as setXXX().

await prefs.setInt('counter', 10);
await prefs.setBool('repeat', true);
await prefs.setDouble('decimal', 1.5);
await prefs.setString('action', 'Start');
await prefs.setStringList('items', <String>['Earth', 'Moon', 'Sun']);

 

If you want to load data, use the form as getXXX().

It is similar to the setXXX() method.

final int? counter = prefs.getInt('counter');
final bool? repeat = prefs.getBool('repeat');
final double? decimal = prefs.getDouble('decimal');
final String? action = prefs.getString('action');
final List<String>? items = prefs.getStringList('items');

 

You can remove an entry using remove() method with a key.

final success = await prefs.remove('counter');

Example

Let's apply this feature to Flutter's default application.

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

...

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

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

  void _incrementCounter() {
    setState(() {
      _counter++;
      _setData(_counter);
    });
  }

  ...

  void _setData(int value) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    await sharedPreferences.setInt('counter', value);
  }

  void _loadData() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    setState(() {
      final int? value = sharedPreferences.getInt('counter');
      if (value == null) {
        _counter = 0;
      } else {
        _counter = value;
      }
    });
  }
}

That's quite simple!

Now, the counter will be kept even after closing the app.

'Dart (Flutter)' 카테고리의 다른 글

[Flutter] Animation  (0) 2022.04.03
[Flutter] File Handling  (0) 2022.04.02
[Flutter] Navigation  (0) 2022.03.30
[Flutter] How to Use Tab Bar Widget  (0) 2022.03.27
[Flutter] Adding Fonts to Flutter Application  (0) 2022.03.26

댓글