在我的应用程序中,我想检测在溅屏如果这个应用程序是第一次启动。为此,我想使用hive nosql包。
之后,如果应用程序是第一次启动,它将打开欢迎页面,如果不是登录页面。
main.dart
import 'package:flutter_config/flutter_config.dart';
import 'package:flutter/material.dart';
import 'package:app/pages/splash/splash_page.dart';
import 'package:hive/hive.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'config/theme/theme.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await FlutterConfig.loadEnvVariables();
await Hive.initFlutter();
await Hive.openBox('settings');
runApp(const App());
}
class App extends StatefulWidget {
const App({Key? key}) : super(key: key);
@override
State<App> createState() => _AppState();
}
class _AppState extends State<App> {
@override
void dispose() async {
Hive.close();
super.dispose();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'App',
debugShowCheckedModeBanner: false,
theme: lightThemeData(context),
darkTheme: darkThemeData(context),
home: const SplashPage(),
);
}
}
splash_page.dart
import 'package:flutter/material.dart';
import 'package:app/pages/login/login_page.dart';
import 'package:app/pages/welcome/welchome_page.dart';
import 'package:app/services/settings_service.dart';
class SplashPage extends StatefulWidget {
const SplashPage({Key? key}) : super(key: key);
@override
State<SplashPage> createState() => _SplashPageState();
}
class _SplashPageState extends State<SplashPage> {
@override
Widget build(BuildContext context) {
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (_) =>
Settings().isFirstTime ? const WelcomePage() : const LoginPage(),
),
);
return const Scaffold(
body: Center(
child: SizedBox(
width: 125,
height: 125,
child: Icon(Icons.clear),
),
),
);
}
}
我调用函数">var _isFirstTime = Settings().isFirstTime;"它应该返回一个bool
settings_service.dart
import 'package:hive/hive.dart';
import 'package:hive_flutter/hive_flutter.dart';
class Settings {
final Box _settingsStorage = Hive.box('settings');
get isFirstTime {
if (_settingsStorage.get('firstRun')) {
return true;
} else {
_settingsStorage.put('firstRun', true);
}
return false;
}
}
i got this error:
════════ Exception caught by widgets library ═══════════════════════════════════
The following _TypeError was thrown building SplashPage(dirty, state: _SplashPageState#261ae):
type 'Null' is not a subtype of type 'bool'
我该如何解决这个问题?以后我想使用设置服务的其他设置以及…
在setting_service.dart中,我想这行->_settingsStorage.get(' firststrn '),返回null。从我的理解你应该做的是,无论何时你得到firststrn为null,你应该赋值它为true。
if (_settingsStorage.get('firstRun') ?? true) {
return _settingsStorage.get('firstRun') ?? true;
}