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

Shared preferences must be initialized error

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

错误:不可为 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());
}

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

在具有 Dart 空安全性(Dart 版本 2.12+)的 Flutter 中,变量必须始终具有一个值,除非您明确声明它们可能是 null.

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

late SharedPreferences localStorage;

这告诉 Flutter “我会在使用前为这个变量分配一个非空值,我保证。”

你可以在 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