Controllare il primo avvio di una app in Flutter
In sostanza vogliamo controllare se è la prima che avviamo una nostra app scritta in Flutter.
Per farlo possiamo usare is_first_run.
C'è da dire che volendo potremmo anche creare la logica "a mano" usando le shared_preferences.
In effetti is_first_run usa proprio quelle dietro le quinte.
Detto ciò, per installare il package:
flutter pub add is_first_run
Qui sotto un esempio:
import 'package:flutter/material.dart';
import 'package:is_first_run/is_first_run.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Test',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(title: 'Flutter Test'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
bool? _isFirstRun;
bool? _isFirstCall;
@override
void initState() {
super.initState();
_checkFirstRun();
_checkFirstCall();
}
void _checkFirstRun() async {
bool ifr = await IsFirstRun.isFirstRun();
setState(() {
_isFirstRun = ifr;
});
}
void _checkFirstCall() async {
bool ifc = await IsFirstRun.isFirstCall();
setState(() {
_isFirstCall = ifc;
});
}
void _reset() async {
await IsFirstRun.reset();
_checkFirstRun();
_checkFirstCall();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
onPressed: _reset,
child: const Text('Reset'),
),
const SizedBox(height: 24),
Text(
'Is first run: ${_isFirstRun != null ? _isFirstRun : 'Unknown'}'),
Text(
'Is first call: ${_isFirstCall != null ? _isFirstCall : 'Unknown'}'),
],
),
),
);
}
}
Come vedete abbiamo due metodi, di vcui vi riporto le descrizioni:
- isFirstRun -> Returns true if this is the first time you call this method since installing the app, otherwise false
- isFirstCall -> Returns true if this is the first time this function has been called since installing the app, otherwise false
Poi c'è reset per fare resettare.
Enjoy!
dart flutter is_first_run shared_preferences
Commentami!