共享首选项必须初始化错误



在flutter中,我遇到了以下关于不可为null变量的错误。我正在使用共享的首选项包来存储设备中的用户信息。我在下面详细添加了错误:

错误:必须初始化不可为null的变量"localStorage"。尝试添加初始值设定项表达式。

shared_preferences:^2.0.9

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
runApp(MyApp());
}
**SharedPreferences localStorage;**
TextEditingController emailController = TextEditingController();
TextEditingController passwordController = TextEditingController();
class MyApp extends StatelessWidget {
static Future init() async {
localStorage = await SharedPreferences.getInstance();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHome(),
);
}
}
class MyHome extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Padding(
padding: const EdgeInsets.all(30.0),
child: Center(
child: Column(
children: [
Padding(
padding: const EdgeInsets.only(top: 200),
),
Container(
margin: EdgeInsets.symmetric(vertical: 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'E-mail Id',
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 15),
),
SizedBox(
height: 10,
),
TextField(
controller: emailController,
obscureText: false,
decoration: InputDecoration(
border: InputBorder.none,
fillColor: Colors.grey,
filled: true,
)),
],
),
),
Container(
margin: EdgeInsets.symmetric(vertical: 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'Password :',
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 15),
),
SizedBox(
height: 10,
),
TextField(
controller: passwordController,
obscureText: false,
decoration: InputDecoration(
border: InputBorder.none,
fillColor: Colors.grey,
filled: true,
)),
],
),
),
ElevatedButton(
onPressed: save,
child: Text('Login'),
),
Padding(
padding: EdgeInsets.only(top: 50),
),
if (localStorage != null)
Padding(
padding: const EdgeInsets.all(15.0),
child: Text(
"User Logged in!!! ->  Email Id: ${localStorage.get('email')}  Password: ${localStorage.get('password')}",
style: TextStyle(fontSize: 20),
),
),
],
),
),
));
}
}
save() async {
await MyApp.init();
localStorage.setString('email', emailController.text.toString());
localStorage.setString('password', passwordController.text.toString());
}

在Flutter with Dart null safety(Dart 2.12+版本(中,除非您特别声明它们可能是null,否则要求变量始终具有值。

对于上面的用例,您可以使用late关键字声明全局localStorage

late SharedPreferences localStorage;

这一消息告诉Flutter;我保证,在使用之前,我会给这个变量分配一个非null值">

你可以在main()中实现这个承诺(顺便说一句,我已经做了async(:

Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
// ↑ Req'd for using SharedPrefs (MethodChannel operations) prior to runApp
localStorage = await SharedPreferences.getInstance();
runApp(const MyApp());
}

然后,您可以按预期使用全局变量localStorage

您必须在正确的状态下初始化SharedPreferences才能使用它,或者尝试将值从MyApp传递到MyHome。

相关内容

  • 没有找到相关文章

最新更新