【问题标题】:Flutter LocalStorage: LateInitializationError: Field 'localStorage' has not been initializedFlutter LocalStorage:LateInitializationError:字段'localStorage'尚未初始化
【发布时间】:2021-08-03 06:52:22
【问题描述】:

我是 Flutter 的新手,我在使用 shared_preferences 为应用程序的自动登录功能时遇到了困难。 这是它的代码。

当异常被抛出时,这是堆栈:

#0 localStorage (package:ui_task/loginform.dart)

#1 MyApp.build (package:ui_task/main.dart:135:8)

#2 StatelessElement.build (package:flutter/src/widgets/framework.dart:4706:28)

#3 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4632:15)

#4 Element.rebuild (package:flutter/src/widgets/framework.dart:4322:5)

bool? isLoginDoneBefore;
void main() {
  runApp(MyApp());
}
// ignore: must_be_immutable
class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  // late bool? isLoginDoneBefore = localStorage.getBool("isLoginSuccessful");
  @override

  void initState() {
    getData();
  }

  getData() async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    isLoginDoneBefore=prefs.getBool("isLoginSuccessful");
  }


  Widget build(BuildContext context) {
    // ignore: unnecessary_null_comparison
    if(localStorage==null || isLoginDoneBefore==null){
      return MaterialApp(
        title: 'Login Form',
        theme: ThemeData(
          primarySwatch: Colors.blueGrey,
        ),
        home: LoginFormWithAutoValidation(),
      );
    }
    else {
      return MaterialApp(
        title: 'Login Form',
        theme: ThemeData(
          primarySwatch: Colors.blueGrey,
        ),
        home: isLoginDoneBefore! ? afterLogin() : LoginFormWithAutoValidation(),
      );
    }
  }
}

更新:添加最顶层的堆栈文件。 这是 loginform.dart:


late SharedPreferences localStorage;

class LoginFormWithAutoValidation extends StatefulWidget {
  @override
  _LoginFormWithAutoValidationState createState() => _LoginFormWithAutoValidationState();

  // static Future init() async{
  //   localStorage = await SharedPreferences.getInstance();
  // }

}

class _LoginFormWithAutoValidationState extends State<LoginFormWithAutoValidation> {

  TextStyle style = TextStyle(fontFamily: 'Montserrat', fontSize: 20.0);

  TextEditingController _passwordController = new TextEditingController();
  TextEditingController _unameController = new TextEditingController();

  final _formKey = new GlobalKey<FormState>();
  late bool isLoginSuccessful;
  late String? _uname;
  late String? _password;
  bool _autoValidate = false;
  save() async{
    // await LoginFormWithAutoValidation.init();
    localStorage.setString('uname',_unameController.text.toString());
    localStorage.setString('password',_passwordController.text.toString());
    localStorage.setBool("isLoginSuccessful",true);
  }
  @override
  Widget build(BuildContext context) {

    return Scaffold(
      backgroundColor: Colors.blueGrey[900],
      body: Center(
        child: SingleChildScrollView(
          child: Padding(
            padding: const EdgeInsets.all(10.0),
            child: Column(
            . . . . .
            Material(
                   // login button
                            
                onPressed: () {
                    if (_formKey.currentState!.validate()) {
                        save();
                        Navigator.push(context,MaterialPageRoute(builder: (context) {
                              return afterLogin();}));
                    } else {
                            setState(() 
                             // validation error
                             _autoValidate = true;
                    });
              }

【问题讨论】:

  • 堆栈跟踪中最顶层的条目是 #0 localStorage (package:ui_task/loginform.dart)。你能提供那个文件的代码吗?
  • 当然我会编辑帖子。

标签: flutter sharedpreferences


【解决方案1】:

您在loginform.dart 文件的顶部定义localStorage,但您没有使用await SharedPreferences.getInstance(); 对其进行初始化,这就是引发错误的原因。除此之外,我不建议将密码以明文形式存储在shared_preferences 中(如果有的话)。它可以很容易地被提取出来。如果您绝对必须存储它,我建议:https://pub.dev/packages/flutter_secure_storage

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-30
    • 2021-11-17
    • 2021-12-01
    • 2022-07-12
    • 1970-01-01
    • 1970-01-01
    • 2022-07-27
    • 2022-06-19
    相关资源
    最近更新 更多