[英]LateInitialization Error In Flutter main.dart
I am developing my app and I don't know why this late Initialization error has come I use this same code in my other apps as well there I don't face such error but in this main file the error is persisting and I have been trying for so long It doesn't works.我正在开发我的应用程序,但我不知道为什么会出现这个迟到的初始化错误我在其他应用程序中也使用了相同的代码,但我没有遇到这样的错误,但在这个主文件中,错误仍然存在,我一直在试了这么久还是不行。
bool? userLoggedIn
bool? userLoggedIn
isn't also working flutter doesn't letting it used. bool? userLoggedIn
也不起作用,flutter 不允许使用它。 Here is my main.dart file code.这是我的 main.dart 文件代码。 Also If anyone can tell me how can I handle 2 logins of app shared preferences that would be a lot helpful
另外,如果有人能告诉我如何处理应用程序共享首选项的 2 次登录,这将很有帮助
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
late bool userLoggedIn;
@override
void initState() {
getLoggedInState();
super.initState();
}
getLoggedInState() async {
await HelperFunctions.getUserLoggedInSharedPreference().then((value) {
setState(() {
userLoggedIn = value!;
});
});
}
@override
Widget build(BuildContext context) {
SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: []);
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Dashee',
theme: ThemeData(
primarySwatch: Colors.deepPurple,
),
home: userLoggedIn ? const Dashboard() : Splash());
}
}
LateInitializationError
means a variable declared using the late keyword was not initialized on the constructor LateInitializationError
表示使用 late 关键字声明的变量未在构造函数上初始化
You declare this boolean variable:你声明这个布尔变量:
late bool userLoggedIn
but did not declare a constructor, so it won't be initialized, the obvious thing to do is giving it a value on the constructor, like so:但是没有声明构造函数,所以它不会被初始化,显而易见的事情是在构造函数上给它一个值,就像这样:
_MyAppState() {
userLoggedIn = false; // just some value so dart doesn't complain.
}
However may I suggest you don't do that and instead simply remove the late
keyword ?但是,我可以建议您不要这样做,而只需删除
late
关键字吗? Doing that, of course, will give you an error because userLoggedIn
is never initialized, but you can fix that by giving it a default value straight on it's declaration or on the constructor initialization:这样做当然会给你一个错误,因为
userLoggedIn
永远不会被初始化,但是你可以通过直接在它的声明或构造函数初始化上给它一个默认值来解决这个问题:
bool userLoggedIn = false;
or或者
_MyAppState(): userLoggedIn = false;
note how on the second option I didn't use the constructor's body, you should only declare a variable late if you plan on initializing it on the constructor's body.请注意在第二个选项中我如何没有使用构造函数的主体,如果您计划在构造函数的主体上初始化变量,则应该仅延迟声明变量。
This should solve the LateInitializationError
that you are getting.这应该可以解决您遇到的
LateInitializationError
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.