🕋

shared_preferencesについて学ぶ🤔

2022/08/31に公開

入力したデータを保存する

shared_preferencesは、カウンターアプリしかサンプルがなくて、理解ができなくて海外の人が作ったNull Safetyに対応していないコードをNull Safety対応にして動くものを作って勉強してみた🧑‍💻

https://pub.dev/packages/shared_preferences

shared_preferencesとは?
単純なデータのためのプラットフォーム固有の永続的ストレージをラップします (iOS と macOS の NSUserDefaults、Android の SharedPreferences など)。データは非同期にディスクに永続化される可能性があり、復帰後にディスクに書き込みが永続化される保証はないため、このプラグインは重要なデータの保存に使用してはならない。

サポートするデータ型は,int, double, bool, String, List<String> です.

一時的にデータを保存する使い方のみ推奨されていて、永続的にデータを保存するなら、SqfLiteかHive他にもあるようですが、ローカルDBを使うことが推奨されています。

サンプルコード

home/home_page.dart

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

class Home extends StatefulWidget {
  const Home({Key? key}) : super(key: key);

  
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  // 初期値を表示するための変数
  String textInit = "初期値";
  // 値を入力するための変数
  final TextEditingController _nameController = TextEditingController();
  // ドキュメント通りに、prefs.setStringで、String型のデータを保存
  _saveData() async {
    // _nameControllerを代入する
    String nameValue = _nameController.text;
    final prefs = await SharedPreferences.getInstance();
    // nameValueを"name"がキーのprefs.setStringで使う。
    await prefs.setString("name", nameValue);
  }
  // ドキュメント通りに、prefs.getStringでString型のデータを取得
  _getData() async {
    final prefs = await SharedPreferences.getInstance();
    setState(() {
      textInit = prefs.getString("name") ?? "値が入っていない!";
    });
  }
  // ドキュメント通りに、prefs.remove("keyの名前")で、ローカルのデータを削除
  // 今回だと、("name")がkeyのデータを削除する
  _removeData() async {
    final prefs = await SharedPreferences.getInstance();
    prefs.remove("name");
    setState(() {
      textInit = "";
    });
  }

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.blueGrey,
        title: Text("ローカルにデータを保存"),
      ),
      body: Container(
        padding: EdgeInsets.all(32),
        child: Column(
          children: [
            Text(
              textInit,
              style: TextStyle(
                fontSize: 20,
              ),
            ),
            TextField(
              keyboardType: TextInputType.text,
              decoration: InputDecoration(labelText: "お名前を入力してください"),
              controller: _nameController,
            ),
            Row(
              children: [
                const SizedBox(width: 30),
                ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    primary: Colors.blue, // background
                    onPrimary: Colors.white, // foreground
                  ),
                  onPressed: _saveData,
                  child: Text('保存'),
                ),
                const SizedBox(width: 30),
                ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    primary: Colors.green, // background
                    onPrimary: Colors.white, // foreground
                  ),
                  onPressed: _getData,
                  child: Text('表示'),
                ),
                const SizedBox(width: 30),
                ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    primary: Colors.red, // background
                    onPrimary: Colors.white, // foreground
                  ),
                  onPressed: _removeData,
                  child: Text('削除'),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

main.dart

import 'package:flutter/material.dart';
import 'package:local_save/screen/home_page.dart';

void main() {
  runApp(const MyApp());
  // runApp(ProviderScope(child: const MyApp()));
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: 'SharedPreferences Demo',
      home: Home(),
    );
  }
}

最後に

今回は、ドキュメントだけだと分かりずらかったので、動くものを使ってどんな仕組みなのか勉強しました。

Discussion