[英]I am implementing Splash Screen in flutter along with it i am using sharedPreferences I am facing late initialisation error in it
Here I have implemented splash screen and in main.dart I assigned it as home:SplashScreen();在这里,我实现了启动画面,在 main.dart 中,我将其指定为 home:SplashScreen(); Here I have also implemented sharedPreferences now I am facing late initialisation error for:static late SharedPreferences pref;
在这里,我还实现了 sharedPreferences,现在我面临以下初始化错误:static late SharedPreferences pref; I can't understand how resolve it and where to declare pref variable import 'package:flutter/material.dart';
我不明白如何解决它以及在哪里声明 pref 变量 import 'package:flutter/material.dart';
import 'package:onesignal_flutter/onesignal_flutter.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'View/LoginPage.dart';
import 'View/homePageAdmin.dart';
class SplashScreen extends StatefulWidget {
@override
State<SplashScreen> createState() => _SplashScreenState();
}
class SharedPrefService {
static late SharedPreferences pref;
static Future<void> init() async {
await SharedPrefService.init();
SharedPrefService.pref = await SharedPreferences.getInstance();
var usrEmail = pref.getString('email');
String usrname = pref.getString('username').toString();
}
}
class _SplashScreenState extends State<SplashScreen> {
String playerId = '';
var usrEmail = SharedPrefService.pref.getString('email');
String usrname = SharedPrefService.pref.getString('username').toString();
@override
void initState() async {
SharedPrefService.pref = await SharedPreferences.getInstance();
super.initState();
await SharedPrefService.init();
initPlatformState();
_navigateToHome();
}
Future<void> initPlatformState() async {
String usrname = SharedPrefService.pref.getString('username').toString();
OneSignal.shared.setAppId('e89acaa4-5388-4e3a-bd69-44d197bdcbd7');
// OneSignal.shared
// .promptUserForPushNotificationPermission()
// .then((accepted) {});
final status = await OneSignal.shared.getDeviceState();
final String? osUserID = status?.userId;
print('The player id from main.dart ...........${osUserID}');
// OneSignal.shared.setNotificationOpenedHandler(
// (OSNotificationOpenedResult result) async {
// var id1 = await result.notification.additionalData!["Docid"];
// final int docid = int.parse(id1).toInt();
// navigatorKey.currentState!.push(MaterialPageRoute(
// builder: (context) => DocumentsDetails(docid, usrname)));
// });
setState(() {
this.playerId = osUserID!;
});
print('this.playerid from main.dart ${this.playerId}');
}
_navigateToHome() async {
String pId = this.playerId;
await Future.delayed(Duration(milliseconds: 1500), () {});
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => usrEmail == null
? LoginPage()
: homePageAdmin(
pId,
usrname,
),
));
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
child: Text(
'Splash Screen',
style: TextStyle(
fontSize: 25,
fontWeight: FontWeight.bold,
color: Colors.blueAccent),
),
),
),
);
}
}
This error occurs when you use late
variable before its initialization.当您在初始化之前使用
late
变量时会发生此错误。
Solution: making late
variable to nullable
variable, for example:解决方案:将
late
变量设为nullable
变量,例如:
class SharedPrefService {
static SharedPreferences? pref; // nullable variable
static Future<void> init() async {
await SharedPrefService.init();
SharedPrefService.pref = await SharedPreferences.getInstance();
var usrEmail = pref?.getString('email');
String usrname = pref!.getString('username').toString();
}
}
You cannot just make initState
async
and expect that to work.您不能只使
initState
async
并期望它起作用。 Yes, it will be async, but since it is still returning void
, it cannot be waited on.是的,它将是异步的,但由于它仍在返回
void
,因此无法等待。 So, it will be called and then your program will continue without waiting for it.因此,它将被调用,然后您的程序将继续执行而无需等待它。
You seem to have a Future
and not really an idea how to handle this inside a Flutter widget.你似乎有一个
Future
而不是真的知道如何在 Flutter 小部件中处理它。 I suggest getting a good overview:我建议得到一个很好的概述:
What is a Future and how do I use it? 什么是 Future 以及如何使用它?
The solution is to use some kind of state management to handle the fact that you are doing something in the background.解决方案是使用某种状态管理来处理您正在后台执行某些操作这一事实。 Your display cannot wait for it.
您的显示器等不及了。 It has to be displayed.
它必须显示出来。 The obvious solution is some kind of spinner or loading screen while you are waiting for the Future to resolve.
显而易见的解决方案是在您等待 Future 解决时使用某种微调器或加载屏幕。 There is a simple example of a
FutureBuilder
in the link above, or you can use more powerful solutions.上面的链接中有一个
FutureBuilder
的简单示例,或者您可以使用更强大的解决方案。 Personally, I prefer bloc , but there are many others, too.就个人而言,我更喜欢bloc ,但也有很多其他的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.