Flutter ローカルストレージ

このセクションでは、Flutter のローカルストレージ方法について説明します。SharedPreferences、ファイルストレージ、SQLite データベースを含みます。


SharedPreferences - 軽量ストレージ

SharedPreferences は、シンプルなキーと値のペアデータの保存に適しています。

依存関係を追加

dependencies:
  shared_preferences: ^2.0.0

例:SharedPreferences の使用

import 'package:shared_preferences/shared_preferences.dart';

// データを保存
Future<void> saveData() async {
  final prefs = await SharedPreferences.getInstance();

  // 文字列を保存
  await prefs.setString('username', '张三');

  // 整数を保存
  await prefs.setInt('age', 25);

  // ブール値を保存
  await prefs.setBool('isLoggedIn', true);

  // リストを保存(JSON 文字列)
  await prefs.setStringList('tags', ['flutter', 'dart']);
}

// データを読み取り
Future<void> loadData() async {
  final prefs = await SharedPreferences.getInstance();

  final username = prefs.getString('username') ?? '';
  final age = prefs.getInt('age') ?? 0;
  final isLoggedIn = prefs.getBool('isLoggedIn') ?? false;
  final tags = prefs.getStringList('tags') ?? [];

  print('ユーザー名: $username');
  print('年齢: $age');
  print('ログイン済み: $isLoggedIn');
  print('タグ: $tags');
}

// データを削除
Future<void> deleteData() async {
  final prefs = await SharedPreferences.getInstance();

  // 単一を削除
  await prefs.remove('username');

  // すべて削除
  await prefs.clear();
}

ファイルストレージ

path_provider を使用してアプリのドキュメントディレクトリを取得し、ファイルストレージを行います。

依存関係を追加

dependencies:
  path_provider: ^2.0.0

例:ファイルの読み書き

import 'dart:io';
import 'package:path_provider/path_provider.dart';

// ドキュメントディレクトリを取得
Future<Directory> get _documentDirectory async {
  return await getApplicationDocumentsDirectory();
}

// ファイルを書き込み
Future<void> writeFile() async {
  final dir = await _documentDirectory;
  final file = File('${dir.path}/my_file.txt');

  // テキストを書き込み
  await file.writeAsString('Hello Flutter!');

  // バイトを書き込み
  final bytes = [72, 101, 108, 108, 111];  // "Hello"
  await file.writeAsBytes(bytes);
}

// ファイルを読み取り
Future<void> readFile() async {
  final dir = await _documentDirectory;
  final file = File('${dir.path}/my_file.txt');

  if (await file.exists()) {
    // テキストを読み取り
    final content = await file.readAsString();
    print('ファイル内容: $content');

    // バイトを読み取り
    final bytes = await file.readAsBytes();
    print('バイト: $bytes');
  }
}

// JSON ファイルストレージ
Future<void> saveJson() async {
  final dir = await _documentDirectory;
  final file = File('${dir.path}/data.json');

  final data = {
    'name': '张三',
    'age': 25,
    'skills': ['Flutter', 'Dart'],
  };

  // jsonEncode を使用して JSON を保存
  await file.writeAsString(jsonEncode(data));
}

SQLite データベース

sqflite を使用して SQLite データベース操作を行います。

依存関係を追加

dependencies:
  sqflite: ^2.0.0
  path: ^1.8.0

例:SQLite の基本操作

import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';

// データベースヘルパークラス
class DatabaseHelper {
  static final DatabaseHelper instance = DatabaseHelper._init();
  static Database? _database;

  DatabaseHelper._init();

  Future<Database> get database async {
    if (_database != null) return _database!;
    _database = await _initDB('my_app.db');
    return _database!;
  }

  // データベースを初期化
  Future<Database> _initDB(String filePath) async {
    final dbPath = await getDatabasesPath();
    final path = join(dbPath, filePath);

    return await openDatabase(
      path,
      version: 1,
      onCreate: _createDB,
    );
  }

  // テーブルを作成
  Future<void> _createDB(Database db, int version) async {
    await db.execute('''
      CREATE TABLE users(
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT NOT NULL,
        email TEXT NOT NULL,
        age INTEGER
      )
    '
'');
  }

  // データを挿入
  Future<int> insertUser(Map<String, dynamic> user) async {
    final db = await database;
    return await db.insert('users', user);
  }

  // すべてのユーザーを照会
  Future<List<Map<String, dynamic>>> getAllUsers() async {
    final db = await database;
    return await db.query('users');
  }

  // 条件付き照会
  Future<List<Map<String, dynamic>>> getUserByName(String name) async {
    final db = await database;
    return await db.query(
      'users',
      where: 'name = ?',
      whereArgs: [name],
    );
  }

  // データを更新
  Future<int> updateUser(int id, Map<String, dynamic> user) async {
    final db = await database;
    return await db.update(
      'users',
      user,
      where: 'id = ?',
      whereArgs: [id],
    );
  }

  // データを削除
  Future<int> deleteUser(int id) async {
    final db = await database;
    return await db.delete(
      'users',
      where: 'id = ?',
      whereArgs: [id],
    );
  }

  // データベースを閉じる
  Future<void> close() async {
    final db = await database;
    db.close();
  }
}

// 使用例
Future<void> dbExample() async {
  final db = DatabaseHelper.instance;

  // ユーザーを追加
  await db.insertUser({
    'name': '张三',
    'email': 'zhangsan@example.com',
    'age': 25,
  });

  // すべてを照会
  final users = await db.getAllUsers();
  print('ユーザーリスト: $users');

  // ユーザーを更新
  await db.updateUser(1, {'name': '李四', 'age': 30});

  // ユーザーを削除
  await db.deleteUser(1);
}

データストレージ方式の選択:単純なキーと値には SharedPreferences、複雑な構造には SQLite、ファイルストレージは大きなファイルに適しています。

その他の拡張