当我想使用共享首选项来存储和显示值时遇到问题。在代码中,我需要创建公共(public)类供下面的函数使用。 但是它会返回以下错误:
错误:必须初始化不可为 null 的实例字段“sharedPreferences”。 ([login] lib/main.dart:32 处的 not_initialized_non_nullable_instance_field)
共享首选项共享首选项;//行:32
这是我的完整代码。
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
import 'package:login/login_page.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: "Code Land",
debugShowCheckedModeBanner: false,
home: MyHomePage(),
theme: ThemeData(
accentColor: Colors.white70
),
);
}
}
class MyHomePage extends StatefulWidget {
@override
createState() => MyHomePageState();
}
class MyHomePageState extends State<MyHomePage> {
SharedPreferences sharedPreferences;
@override
void initState() {
super.initState();
checkLoginStatus();
}
checkLoginStatus() async {
sharedPreferences = await SharedPreferences.getInstance();
if(sharedPreferences.getString("token") == null) {
Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (BuildContext context) => LoginPage()), (Route<dynamic> route) => false);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Code Land", style: TextStyle(color: Colors.white)),
actions: <Widget>[
FlatButton(
onPressed: () {
sharedPreferences.clear();
sharedPreferences.commit();
Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (BuildContext context) => LoginPage()), (Route<dynamic> route) => false);
},
child: Text("Log Out", style: TextStyle(color: Colors.white)),
),
],
),
body: Center(child: Text("Main Page")),
drawer: Drawer(),
);
}
}```
最佳答案
像这样更改该行,以便编译器知道您稍后将对其进行初始化:
late SharedPreferences sharedPreferences;
关于Flutter SharedPreferences 不可为 null 的实例字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69359360/