22
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Flutterで[key : value] 形式でローカルにデータを保存する

Last updated at Posted at 2018-05-20

Androidでいうところの SharedPreferences
iOSでいうところの UserDefaults

をFlutterで使う方法を書いていきます。

Packageの導入

Packageが用意されているのでこれを使います。

いつも通り、下記をpubspec.ymlに下記を追加します。


dependencies:
  flutter:
    sdk: flutter
  shared_preferences: ^0.4.1

追加したら下記を実行

flutter get packages

実装

保存、取得、削除 それぞれで async await を使うので注意が必要です。

保存

saveData(String email) async {

    SharedPreferences pref = await SharedPreferences.getInstance();
    await pref.setString("displayName", user.email);
}

取得

getData() async {

    SharedPreferences pref = await SharedPreferences.getInstance();
    setState(() {
      userName = preferences.get("displayName");
    });
}

このメソッドを initState メソッドとかで呼ぶとデータを取得できます。

削除


removeData(String key) async {

    SharedPreferences pref = await SharedPreferences.getInstance();
    await pref.remove(key);
}

両OS一発でできるのはほんと楽だな〜

22
13
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?