Вы можете скопировать вставить полный код ниже
Шаг 1: Вы можете поместить logi c checkFirstTime()
в main()
Шаг 2: Чтобы использовать updateFirstTime()
в build
, вы можете использовать initialRoute
чтобы избежать seen
значение обновления причины SingupScreen()
внезапно изменится на HomeScreen()
фрагмент кода
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
SharedPreferences prefs = await SharedPreferences.getInstance();
seen = (prefs.getBool('seen') ?? false);
runApp(MyApp());
}
...
initialRoute: seen == false || seen == null ? "/sign" : "/",
routes: {
'/': (context) => HomeScreen(
title: "demo",
),
"/sign": (context) => SignUpScreen(),
рабочая демонстрация
полный код
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/services.dart';
bool seen;
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
SharedPreferences prefs = await SharedPreferences.getInstance();
seen = (prefs.getBool('seen') ?? false);
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
initialRoute: seen == false || seen == null ? "/sign" : "/",
routes: {
'/': (context) => HomeScreen(
title: "demo",
),
"/sign": (context) => SignUpScreen(),
},
);
}
}
class SignUpScreen extends StatelessWidget {
_updateFirstTime() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
seen = true;
prefs.setBool('seen', true);
}
@override
Widget build(BuildContext context) {
if (seen == false) {
_updateFirstTime();
}
return Text('SignUpScreen');
}
}
class HomeScreen extends StatefulWidget {
HomeScreen({Key key, this.title}) : super(key: key);
final String title;
@override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}