📦

ローカルデータベース(shared_preferences)を使ってみた

2024/05/21に公開

はじめに

ローカルDB第二弾ということでshared_preferencesを実装してみました。

shared_preferencesとは

Wraps platform-specific persistent storage for simple data (NSUserDefaults on iOS and macOS, SharedPreferences on Android, etc.). Data may be persisted to disk asynchronously, and there is no guarantee that writes will be persisted to disk after returning, so this plugin must not be used for storing critical data.
Supported data types are int, double, bool, String and List<String>

要するに、このパッケージを使えばシンプルなローカルに保存できるけど重要なデータの保存には使わないでくださいね。
このパッケージでサポートされているデータの型は int, double, bool, String and List<String>だよ。

※shared_preferences公式
https://pub.dev/packages/shared_preferences

実装例

さっそくですが、実装例を作成してみました。

記載内容

  • Write data
    • setSaveName
  • Read data
    • getName
  • Delete data
    • deleteName

local_db_repo.dart

import 'package:shared_preferences/shared_preferences.dart';

class LocalDBRepo {
  //1.キーを定義
  final String keyName = 'name';

  //保存
  Future<void> setSaveName(String name) async {
    final String newName = name;
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(keyName, newName);
  }

  //取得
  Future<String?> getName() async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getString(keyName) ?? '';
  }

  //削除
  Future<void> deleteName() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove(keyName);
  }
}

first_page.dart


class FirstPage extends StatefulWidget {
  const FirstPage({super.key});

  
  State<FirstPage> createState() => _FirstPageState();
}

class _FirstPageState extends State<FirstPage> {
  final TextEditingController nameController = TextEditingController();
  final LocalDBRepo localDBRepo = LocalDBRepo();
  String _name = '';

  
  void initState() {
    super.initState();
    _loadName();
  }

  
  void dispose() {
    nameController.dispose();
    super.dispose();
  }

  Future<void> _loadName() async {
    String? loadedName = await localDBRepo.getName();
    //UIの更新
    setState(() {
      _name = loadedName ?? '';
    });
  }

  Future<void> _clearName() async {
    await localDBRepo.deleteName();
    await _loadName();
  }

  Future<void> _saveName() async {
    await localDBRepo.setSaveName(nameController.text);
    await _loadName();
    nameController.clear();
  }

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              //nameController.text,
              _name,
              style: const TextStyle(fontSize: 20),
            ),
            const SizedBox(height: 30),
            SizedBox(
              width: 250,
              child: TextField(
                decoration: const InputDecoration(
                  border: OutlineInputBorder(),
                  labelText: 'name',
                ),
                controller: nameController,
              ),
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                ElevatedButton(
                  onPressed: _clearName,
                  child: const Text('clear'),
                ),
                const SizedBox(width: 10),
                ElevatedButton(
                  onPressed: _saveName,
                  child: const Text('save'),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

main.dart

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const FirstPage(),
    );
  }
}

Discussion