「Flutter/外部ライブラリ/shared preferences」の版間の差分
提供: 初心者エンジニアの簡易メモ
(→サンプル) |
(→サンプル) |
||
行14: | 行14: | ||
import 'package:shared_preferences/shared_preferences.dart'; | 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 | ||
+ | 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( | floatingActionButton: FloatingActionButton( | ||
onPressed: _incrementCounter, | onPressed: _incrementCounter, | ||
行20: | 行50: | ||
child: Icon(Icons.add), | child: Icon(Icons.add), | ||
), // This trailing comma makes auto-formatting nicer for build methods. | ), // This trailing comma makes auto-formatting nicer for build methods. | ||
− | + | ); | |
− | + | } | |
− | + | ||
− | + | ||
− | + | ||
− | + | ||
} | } | ||
</pre> | </pre> |
2019年4月26日 (金) 18:11時点における版
pubspec.yaml
dependencies: flutter: sdk: flutter shared_preferences: ^0.5.2
flutter packages get
サンプル
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 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. ); } }