🐙
【Flutter】アプリの起動回数を取得【超簡易メモ】
参考
手順
- アプリの起動回数をローカル保存
- 起動時に回数を+1回する
// ローカルにデータ保存するライブラリ
import 'package:shared_preferences/shared_preferences.dart';
// インスタンス生成
final Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
// with WidgetsBindingObserver が必要
class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
// ~~~~省略~~~~
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
}
void didChangeAppLifecycleState(AppLifecycleState state) async {
// アプリ起動時、起動回数を +1 する(resumedが起動時)
if (state == AppLifecycleState.resumed) {
final SharedPreferences prefs = await _prefs;
final int count = prefs.getInt("launchCount") ?? 0;
prefs.setInt("launchCount", count + 1);
}
}
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
}
Discussion