「Flutter/外部ライブラリ/shared preferences」の版間の差分
提供: 初心者エンジニアの簡易メモ
(→値設定、値取得) |
(→ListIntを保存、取得するとき) |
||
(同じ利用者による、間の21版が非表示) | |||
行1: | 行1: | ||
+ | ==shared_preferencesとは== | ||
+ | 値を端末に保存できるライブラリ | ||
+ | |||
==shared_preferencesをインストール== | ==shared_preferencesをインストール== | ||
pubspec.yaml | pubspec.yaml | ||
行10: | 行13: | ||
flutter packages get | flutter packages get | ||
− | == | + | ==prefで値設定、値取得== |
準備 | 準備 | ||
import 'package:shared_preferences/shared_preferences.dart'; | import 'package:shared_preferences/shared_preferences.dart'; | ||
− | + | 数値取得 | |
void _incrementCounter() async { | void _incrementCounter() async { | ||
SharedPreferences prefs = await SharedPreferences.getInstance(); | SharedPreferences prefs = await SharedPreferences.getInstance(); | ||
行20: | 行23: | ||
} | } | ||
− | + | 数値設定 | |
void _incrementCounter() async { | void _incrementCounter() async { | ||
SharedPreferences prefs = await SharedPreferences.getInstance(); | SharedPreferences prefs = await SharedPreferences.getInstance(); | ||
行26: | 行29: | ||
} | } | ||
asyncで囲む必要がある | asyncで囲む必要がある | ||
+ | |||
+ | ===文字列設定・取得=== | ||
+ | String name = prefs.getString("name"); | ||
+ | name = "${name} ${counter}"; | ||
+ | await prefs.setString('name', name); | ||
+ | |||
+ | ===文字列リスト設定・取得=== | ||
+ | SharedPreferences prefs = await SharedPreferences.getInstance(); | ||
+ | List<String> names = prefs.getStringList("textnames"); | ||
+ | if (names == null) { | ||
+ | names = new List<String>(); | ||
+ | } | ||
+ | names.add("new text"); | ||
+ | names.forEach((item) { | ||
+ | print(item); | ||
+ | }); | ||
+ | await prefs.setStringList('textnames', names); | ||
+ | |||
+ | ==別クラスを使う場合== | ||
+ | lib/model/Pref.dart | ||
+ | <pre> | ||
+ | import 'package:shared_preferences/shared_preferences.dart'; | ||
+ | class Pref { | ||
+ | static void saveNames(List<String> names) async { | ||
+ | SharedPreferences prefs = await SharedPreferences.getInstance(); | ||
+ | await prefs.setStringList('textnames', names); | ||
+ | } | ||
+ | static Future<List<String>> getNames() async { | ||
+ | SharedPreferences prefs = await SharedPreferences.getInstance(); | ||
+ | List<String> names = prefs.getStringList("textnames"); | ||
+ | if (names == null) { | ||
+ | names = new List<String>(); | ||
+ | } | ||
+ | return names; | ||
+ | } | ||
+ | } | ||
+ | </pre> | ||
+ | lib/main.dart | ||
+ | Prefでgetしてきたものは必ずsetState((){})で囲って値を更新させて表示に反映させる | ||
+ | <pre> | ||
+ | import 'model/pref.dart'; | ||
+ | List<String> names = new List<String>(); | ||
+ | Pref.getNames().then((value) { | ||
+ | setState(() { | ||
+ | names = value; | ||
+ | }); | ||
+ | names.add("hogehoge"); | ||
+ | names.forEach((item) { | ||
+ | print(item); | ||
+ | }); | ||
+ | Pref.saveNames(names); | ||
+ | }); | ||
+ | </pre> | ||
==サンプル== | ==サンプル== | ||
行75: | 行131: | ||
} | } | ||
</pre> | </pre> | ||
+ | |||
+ | ==ListIntを保存、取得するとき== | ||
+ | <pre> | ||
+ | static Future<List<int>> getListInt(String key) async { | ||
+ | SharedPreferences prefs = await SharedPreferences.getInstance(); | ||
+ | String intsStr = prefs.getString(key); | ||
+ | intsStr = intsStr.replaceAll("[", ""); | ||
+ | intsStr = intsStr.replaceAll("]", ""); | ||
+ | intsStr = intsStr.replaceAll(" ", ""); | ||
+ | print("intsStr=" + intsStr); | ||
+ | List<String> intSplit = intsStr.split(","); | ||
+ | List<int> ids = new List<int>(); | ||
+ | for (String id in intSplit) { | ||
+ | print("id=" + id); | ||
+ | ids.add(int.parse(id)); | ||
+ | } | ||
+ | return ids; | ||
+ | } | ||
+ | static void setListInt(String key, List<int> ids) async { | ||
+ | SharedPreferences prefs = await SharedPreferences.getInstance(); | ||
+ | await prefs.setString(key, ids.toString()); | ||
+ | } | ||
+ | static void saveArticleIds(List<int> articleIds) async { | ||
+ | await setListInt(articleIdsKey, articleIds); | ||
+ | } | ||
+ | static Future<List<int>> getArticleIds() async { | ||
+ | List<int> articleIds = await getListInt(articleIdsKey); | ||
+ | if (articleIds == null || articleIds.length == 0) { | ||
+ | articleIds = articleIdsDefault; | ||
+ | } | ||
+ | return articleIds; | ||
+ | } | ||
+ | </pre> | ||
+ | |||
+ | ==Unhandled Exception: MissingPluginException(No implementation found for method getAll on channel plugins.flutter.io/shared_preferencesエラーが起こるとき== | ||
+ | flutter run | ||
==参考== | ==参考== | ||
− | + | 公式shared_preferences:https://pub.dartlang.org/packages/shared_preferences | |
+ | |||
+ | 公式shared_preferences-class:https://pub.dartlang.org/documentation/shared_preferences/latest/shared_preferences/SharedPreferences-class.html | ||
+ | Flutterで[key : value] 形式でローカルにデータを保存する | ||
https://qiita.com/superman9387/items/4786ba4208a546842176 | https://qiita.com/superman9387/items/4786ba4208a546842176 |
2019年12月10日 (火) 14:33時点における最新版
目次
値を端末に保存できるライブラリ
pubspec.yaml
dependencies: flutter: sdk: flutter shared_preferences: ^0.5.2
flutter packages get
prefで値設定、値取得
準備
import 'package:shared_preferences/shared_preferences.dart';
数値取得
void _incrementCounter() async { SharedPreferences prefs = await SharedPreferences.getInstance(); int counter = prefs.getInt('counter'); }
数値設定
void _incrementCounter() async { SharedPreferences prefs = await SharedPreferences.getInstance(); await prefs.setInt('counter', 10); }
asyncで囲む必要がある
文字列設定・取得
String name = prefs.getString("name"); name = "${name} ${counter}"; await prefs.setString('name', name);
文字列リスト設定・取得
SharedPreferences prefs = await SharedPreferences.getInstance(); List<String> names = prefs.getStringList("textnames"); if (names == null) { names = new List<String>(); } names.add("new text"); names.forEach((item) { print(item); }); await prefs.setStringList('textnames', names);
別クラスを使う場合
lib/model/Pref.dart
import 'package:shared_preferences/shared_preferences.dart'; class Pref { static void saveNames(List<String> names) async { SharedPreferences prefs = await SharedPreferences.getInstance(); await prefs.setStringList('textnames', names); } static Future<List<String>> getNames() async { SharedPreferences prefs = await SharedPreferences.getInstance(); List<String> names = prefs.getStringList("textnames"); if (names == null) { names = new List<String>(); } return names; } }
lib/main.dart Prefでgetしてきたものは必ずsetState((){})で囲って値を更新させて表示に反映させる
import 'model/pref.dart'; List<String> names = new List<String>(); Pref.getNames().then((value) { setState(() { names = value; }); names.add("hogehoge"); names.forEach((item) { print(item); }); Pref.saveNames(names); });
サンプル
import 'package:shared_preferences/shared_preferences.dart'; class _MyHomePageState extends State<MyHomePage> { int _counter = 0; _incrementCounter() async { SharedPreferences prefs = await SharedPreferences.getInstance(); int counter = (prefs.getInt('counter') ?? 0) + 1; print('Pressed $counter times.'); await prefs.setInt('counter', counter); setState(() { _counter = counter; }); } @override void initState(){ _incrementCounter(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( 'HelloWorld:', ), Text( '$_counter', style: Theme.of(context).textTheme.display1, ), ], ), ), floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: Icon(Icons.add), ), // This trailing comma makes auto-formatting nicer for build methods. ); } }
ListIntを保存、取得するとき
static Future<List<int>> getListInt(String key) async { SharedPreferences prefs = await SharedPreferences.getInstance(); String intsStr = prefs.getString(key); intsStr = intsStr.replaceAll("[", ""); intsStr = intsStr.replaceAll("]", ""); intsStr = intsStr.replaceAll(" ", ""); print("intsStr=" + intsStr); List<String> intSplit = intsStr.split(","); List<int> ids = new List<int>(); for (String id in intSplit) { print("id=" + id); ids.add(int.parse(id)); } return ids; } static void setListInt(String key, List<int> ids) async { SharedPreferences prefs = await SharedPreferences.getInstance(); await prefs.setString(key, ids.toString()); } static void saveArticleIds(List<int> articleIds) async { await setListInt(articleIdsKey, articleIds); } static Future<List<int>> getArticleIds() async { List<int> articleIds = await getListInt(articleIdsKey); if (articleIds == null || articleIds.length == 0) { articleIds = articleIdsDefault; } return articleIds; }
flutter run
参考
公式shared_preferences:https://pub.dartlang.org/packages/shared_preferences
公式shared_preferences-class:https://pub.dartlang.org/documentation/shared_preferences/latest/shared_preferences/SharedPreferences-class.html
Flutterで[key : value] 形式でローカルにデータを保存する https://qiita.com/superman9387/items/4786ba4208a546842176