我构建了一个函数,该函数用于以共享首选项存储令牌,然后在我第一次运行我的应用程序时从服务器获取数据
在构建AdminPage(dirty, 状态:AdminPageState#87bcd):颤动:方法“ []”被调用 空值。颤动:接收方:空颤动:尝试调用:
然后该应用程序可以正常运行
P.S。我的代码是
Future<Map<String, dynamic>> getCards(String userid) async {
BuildContext context;
String jWTtoken = '';
try {
final SharedPreferences prefs = await SharedPreferences.getInstance();
// prefs = await SharedPreferences.getInstance();
jWTtoken = prefs.getString('token');
tokenfoo();
} catch (e) {
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (BuildContext context) => AuthPage()),
);
}
final Map<String, dynamic> authData = {
'Userid': '261',
// 'Email':_formData['Email'],
// 'Password':_formData['Password'],
};
final http.Response response = await http.post(
'hurl',
body: json.encode(authData),
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + jWTtoken
});
final Map<String, dynamic> responseData = json.decode(response.body);
if (responseData["StatusCode"] == 200) {
null;
} else if (responseData["StatusCode"] == 401) {
print(responseData);
Logout();
} else {
print(responseData);
Logout();
null;
}
return responseData;
}
有什么事吗?
,在调试模式下,此行中显示错误
final SharedPreferences prefs = await SharedPreferences.getInstance();
错误:
══╡小工具图书馆的例外情况提示 ╞═════════════════════════════════════════════════ ══════════扑: 在构建AdminPage(dirty, 状态:AdminPageState#7db9a):颤动:方法'[]'被调用 空值。颤动:接收者:空颤动:尝试调用:颤动: flutter:引发异常时,这是堆栈:flutter:
0 Object.noSuchMethod(dart:core / runtime / libobject_patch.dart:50:5)颤抖:#1
AdminPageState.build(package:idb / pages / adminpage.dart:63:39)扑朔迷离:
2 StatefulElement.build(package:flutter / src / widgets / framework.dart:3809:27)飘动:#3
ComponentElement.performRebuild (package:flutter / src / widgets / framework.dart:3721:15)flutter:#4
Element.rebuild(包:flutter / src / widgets / framework.dart:3547:5) 颤抖:#5 ComponentElement._firstBuild (package:flutter / src / widgets / framework.dart:3701:5)flutter:#6
StatefulElement._firstBuild (package:flutter / src / widgets / framework.dart:3848:11)flutter:#7
ComponentElement.mount (package:flutter / src / widgets / framework.dart:3696:5)flutter:#8
Element.inflateWidget (package:flutter / src / widgets / framework.dart:2950:14)flutter:#9
Element.updateChild (package:flutter / src / widgets / framework.dart:2753:12)flutter:#10
ComponentElement.performRebuild (package:flutter / src / widgets / framework.dart:3732:16)flutter:#11
Element.rebuild(包:flutter / src / widgets / framework.dart:3547:5) 颤抖:#12 BuildOwner.buildScope (package:flutter / src / widgets / framework.dart:2286:33)flutter:#13
_WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding&WidgetsBinding.drawFrame (package:flutter / src / widgets / binding.dart:676:20)flutter:#14
_WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding._handlePersistentFrameCallback (package:flutter / src / rendering / binding.dart:219:5)flutter:#15
_WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._invokeFrameCallback (package:flutter / src / scheduler / binding.dart:990:15)flutter:#16
_WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding.handleDrawFrame (package:flutter / src / scheduler / binding.dart:930:9)flutter:#17
_WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._handleDrawFrame (package:flutter / src / scheduler / binding.dart:842:5)flutter:#18
_invoke(dart:ui / hooks.dart:154:13)颤抖:#19 _drawFrame(dart:ui / hooks.dart:143:3)
答案 0 :(得分:0)
可能是因为jwToken在初始化时为空。尝试给jwToken一个字符串值,例如“ test”。
答案 1 :(得分:0)
发生这种情况是因为您在使用前没有对其进行初始化
为避免这种情况,您应该像这样在 await SharedPref.init();
方法中的 _MyAppState
类上初始化 initState()
class _MyAppState extends State<MyApp> {
void initState() async {
super.initState();
await SharedPref.init();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
locale: _locale,
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: appThemeColor,
accentColor: Colors.lightBlueAccent,
),
home: SplashScreen(),
builder: (BuildContext context, Widget child) {
return child;
},
);
}
}
创建一个全局类以供全局使用
class SharedPref {
static SharedPreferences pref;
static Future init() async {
pref = await SharedPreferences.getInstance();
}
}
以后就可以这样使用了
SharedPref.pref.setBool("isLogin", true);