【发布时间】:2021-12-31 10:31:07
【问题描述】:
在颤动中,我遇到了关于不可为空变量的以下错误。我正在使用共享首选项包将用户信息存储在设备中。我在下面详细添加了错误:
错误:必须初始化不可为空的变量“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 dart sharedpreferences