Dart登录页SharedPreferences读取值返回null显示为文本问题求助
问题描述
使用Dart开发应用时,登录页面初始化阶段从SharedPreferences读取邮箱和密码值返回null,导致输入框直接显示“null”文本。
相关代码
class _LoginScreenState extends State<LoginScreen> { final TextEditingController _emailController = TextEditingController(); final TextEditingController _passwordController = TextEditingController(); bool checkSaveData = false; SharedPreferences? pref; @override void initState() { loadSharedPreferences (); super.initState(); } loadSharedPreferences () async{ pref = await SharedPreferences.getInstance(); if(pref !=null){ _emailController.text=pref.getString("email").toString(); _passwordController.text=pref.getString("password").toString(); setState(() {}); print(pref.getString("email")); print(pref.getString("password")); } } } Padding( padding: const EdgeInsets.all(10), child: Column( children: [ TextField( decoration: const InputDecoration( label: Text("Email"), prefixIcon: Icon(Icons.person), border: OutlineInputBorder(), ), controller: _emailController, ), const SizedBox( height: 20, ), TextField( decoration: const InputDecoration( label: Text("clave"), prefixIcon: Icon(Icons.lock), border: OutlineInputBorder(), ), controller: _passwordController, obscureText: true, ), const SizedBox( height: 10, ), Consumer<AuthService>( builder: (context, authServiceProvider, child) { return SizedBox( height: 60, width: double.infinity, child: authServiceProvider.isLoading ? const Center( child: CircularProgressIndicator(), ) : ElevatedButton( onPressed: () { authServiceProvider.loginWorker( _emailController.text.trim(), _passwordController.text.trim(), context); if(checkSaveData && pref !=null){ pref!.setString("email", _emailController.text!); pref!.setString("password", _passwordController.text!); } }, style: ElevatedButton.styleFrom( //backgroundColor: Colors.tealAccent[600], backgroundColor: Color.fromRGBO(114, 153, 160, 10), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(30))), child: const Text( "LOGIN", style: TextStyle(fontSize: 20), ), ), ); }, ), CheckboxListTile( value: checkSaveData, title: const Text('save data', style: TextStyle(color: Colors.blueGrey),), onChanged: (value) { setState(() { checkSaveData=value!; }); }), ), ),
问题截图

解决方法
1. 处理null值,避免显示"null"字符串
当SharedPreferences中未存储对应键值时,pref.getString()会返回null,直接调用.toString()会将null转为字符串"null"。改用空值合并运算符??,当值为null时赋值为空字符串:
loadSharedPreferences () async{ pref = await SharedPreferences.getInstance(); if(pref !=null){ // 用空值合并运算符替换toString() _emailController.text = pref.getString("email") ?? ""; _passwordController.text = pref.getString("password") ?? ""; setState(() {}); print(pref.getString("email")); print(pref.getString("password")); } }
2. 修正initState生命周期顺序
State的initState方法必须先调用父类的super.initState(),再执行自定义逻辑,否则可能引发生命周期异常:
@override void initState() { super.initState(); // 移到第一行 loadSharedPreferences(); }
3. 优化保存数据的代码
TextEditingController的text属性本身就是非空字符串,无需加!断言:
if(checkSaveData && pref !=null){ pref!.setString("email", _emailController.text); // 去掉! pref!.setString("password", _passwordController.text); // 去掉! }
内容的提问来源于stack exchange,提问作者jose andres inga medina
相关产品推荐
相关产品推荐

