我正在開發我的應用程式,但我不知道為什么會出現這個遲到的初始化錯誤 我在其他應用程式中也使用了相同的代碼,但我沒有遇到此類錯誤,但在此主檔案中,錯誤仍然存??在,我一直試了這么久還是不行。bool? userLoggedIn也不是作業顫振不讓它使用。這是我的 main.dart 檔案代碼。另外,如果有人能告訴我如何處理應用程式共享首選項的 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());
}
}
uj5u.com熱心網友回復:
LateInitializationError 表示使用 late 關鍵字宣告的變數未在建構式上初始化
你宣告這個布爾變數:
late bool userLoggedIn
但是沒有宣告建構式,所以它不會被初始化,顯而易見的事情是在建構式上給它一個值,就像這樣:
_MyAppState() {
userLoggedIn = false; // just some value so dart doesn't complain.
}
但是,我可以建議您不要這樣做,而只需洗掉late關鍵字嗎?這樣做,當然,會給你一個錯誤,因為userLoggedIn它從未被初始化,但你可以通過在它的宣告或建構式初始化時直接給它一個默認值來解決這個問題:
bool userLoggedIn = false;
或者
_MyAppState(): userLoggedIn = false;
請注意在第二個選項中我如何沒有使用建構式的主體,如果您計劃在建構式的主體上初始化變數,則應該僅延遲宣告變數。
這應該解決LateInitializationError你得到的問題。
關于多次登錄
如果您想擁有三個(或更多!)登錄狀態,我建議您宣告這些狀態的列舉:
enum LogInState {
LoggedOff,
LoggedInAsRider,
LoggedInAsUser,
}
為了將所述狀態存盤在 sharedPreferences 中,您可以將它們存盤為整數:
Future<void> savedLoggedInState(LogInState state) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setInt('some key', state.index);
}
然后從共享首選項中讀取所述值:
Future<LogInState> getLoginState() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
int index = prefs.getInt('some key') ?? 0;
return LogInState.values[index];
}
最后要顯示每個不同的登錄狀態,你會做這樣的事情:
home: _getLogInScreen(),
[...]
Widget _getLogInScreen() {
switch (userLogIn) {
case LogInState.LoggedOff:
return Splash();
case LogInState.LoggedInAsRider:
return RiderDashboard();
case LogInState.LoggedInAsUser:
return UserDashBoard();
}
// if you make a new log in state, you need to add it to the switch
// statement or it will throw an unimplemented error
throw UnimplementedError();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/358857.html
