SharedPreferences:未处理的异常:对空值使用空检查运算符

时间:2021-06-13 21:54:41

标签: flutter dart flutter-sharedpreference

这是整个代码文件 在 getInstance() 上运行 SharedPreferences 时,它会抛出“用于空值的空检查运算符”错误。但在 initState

中调用 getInstance 时有效
import 'package:flutter/material.dart';

import 'package:shared_preferences/shared_preferences.dart';

main(List<String> args) {
  runApp(MaterialApp(home: MyApp()));
}

// ignore: must_be_immutable
class MyApp extends StatefulWidget {
  SharedPreferences sharedPreferences;
  MyApp() {
    SharedPreferences.getInstance().then((value) {
      sharedPreferences = value;
    });
  }
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Center(
      child: Column(
        children: [
          Text(
            "${(widget.sharedPreferences != null) ? 
widget.sharedPreferences.getInt('count') ?? 'no count found' : ''}",
              ),
              ElevatedButton(
                onPressed: () => setState(() {}),
                child: Text("setState"),
              ),
            ],
          ),
        ));
      }
}

为什么会这样?

0 个答案:

没有答案