【问题标题】:Shared preferences must be initialized error必须初始化共享首选项错误
【发布时间】: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


    【解决方案1】:

    在具有 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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-23
        • 2022-11-25
        • 1970-01-01
        • 2023-02-13
        • 2020-09-15
        • 1970-01-01
        • 2021-02-16
        • 2021-09-04
        相关资源
        最近更新 更多