facebook twitter hatena line email

Flutter/外部ライブラリ/shared preferences

提供: 初心者エンジニアの簡易メモ
2019年4月28日 (日) 17:45時点におけるAdmin (トーク | 投稿記録)による版 (値設定、値取得)

移動: 案内検索

shared_preferencesをインストール

pubspec.yaml

dependencies:
  flutter:
    sdk: flutter
  shared_preferences: ^0.5.2

flutter packages get

値設定、値取得

準備

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);

サンプル

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.
    );
  }
}

参考

公式:https://pub.dartlang.org/packages/shared_preferences

https://qiita.com/superman9387/items/4786ba4208a546842176