概要
この記事ではshared_preferencesパッケージを使用した、簡易的な設定情報保存について述べている。
必ずしも成功するとは限らない。
getしたデータを変数に読み込む際は、必ずsetState(() {.....}); で行わなければならない。
起動後の初期化は、initState() {} から、_readSetting(); を呼び出せる。
パッケージの導入
flutter pub add shared_preferences
pubspec.yaml
でインストール完了とバージョンを確認しとく。
サンプルソース
設定を扱う .dart ファイルに以下のインポート文を追記
import 'package:shared_preferences/shared_preferences.dart';
.getXxx()
, .setXxx()
を使用して、どこかで以下のような処理を追加する ("Xxx" は変数型によって様々。詳細は公式の仕様を参照)
final int counter=0;
final String name ='';
final bool isSelected=false;
// 設定値を取得
void _readSetting() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
counter = (prefs.getInt('counter') ?? 0) + 1;
name = prefs.getString('name') ?? '';
isSelected = prefs.getBool('isSelected') ?? false;
});
}
// 設定値を保存
void _saveSetting() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setInt('counter', 777);
await prefs.setString('name', 'Yamada');
await prefs.setBool('isSelected', true);
}
// 設定値を削除
void _deleteSetting() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
// 型に関係なくキー名を指定するだけ
await prefs.remove('counter');
await prefs.remove('name');
await prefs.remove('isSelected');
}
void initState() {
super.initState();
// ウィジェットの初期化処理をここに記述
_readSetting();
}
.getXxx()
は、設定値が存在しない場合は Null を返す可能性があるため、 ??
演算子を用いて右項に初期値を設定する必要がある。
パッケージチームのサンプルソース
main.dart
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: public_member_api_docs
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
// #docregion migrate
import 'package:shared_preferences/util/legacy_to_async_migration_util.dart';
// #enddocregion migrate
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'SharedPreferencesWithCache Demo',
home: SharedPreferencesDemo(),
);
}
}
class SharedPreferencesDemo extends StatefulWidget {
const SharedPreferencesDemo({super.key});
@override
SharedPreferencesDemoState createState() => SharedPreferencesDemoState();
}
class SharedPreferencesDemoState extends State<SharedPreferencesDemo> {
final Future<SharedPreferencesWithCache> _prefs =
SharedPreferencesWithCache.create(
cacheOptions: const SharedPreferencesWithCacheOptions(
// This cache will only accept the key 'counter'.
allowList: <String>{'counter'}));
late Future<int> _counter;
int _externalCounter = 0;
Future<void> _incrementCounter() async {
final SharedPreferencesWithCache prefs = await _prefs;
final int counter = (prefs.getInt('counter') ?? 0) + 1;
setState(() {
_counter = prefs.setInt('counter', counter).then((_) {
return counter;
});
});
}
/// Gets external button presses that could occur in another instance, thread,
/// or via some native system.
Future<void> _getExternalCounter() async {
final SharedPreferencesAsync prefs = SharedPreferencesAsync();
setState(() async {
_externalCounter = (await prefs.getInt('externalCounter')) ?? 0;
});
}
Future<void> _migratePreferences() async {
// #docregion migrate
const SharedPreferencesOptions sharedPreferencesOptions =
SharedPreferencesOptions();
final SharedPreferences prefs = await SharedPreferences.getInstance();
await migrateLegacySharedPreferencesToSharedPreferencesAsyncIfNecessary(
legacySharedPreferencesInstance: prefs,
sharedPreferencesAsyncOptions: sharedPreferencesOptions,
migrationCompletedKey: 'migrationCompleted',
);
// #enddocregion migrate
}
@override
void initState() {
super.initState();
_migratePreferences().then((_) {
_counter = _prefs.then((SharedPreferencesWithCache prefs) {
return prefs.getInt('counter') ?? 0;
});
_getExternalCounter();
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('SharedPreferencesWithCache Demo'),
),
body: Center(
child: FutureBuilder<int>(
future: _counter,
builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
case ConnectionState.waiting:
return const CircularProgressIndicator();
case ConnectionState.active:
case ConnectionState.done:
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
return Text(
'Button tapped ${snapshot.data ?? 0 + _externalCounter} time${(snapshot.data ?? 0 + _externalCounter) == 1 ? '' : 's'}.\n\n'
'This should persist across restarts.',
);
}
}
})),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}