#flutter #dart #sharedpreferences
#flutter #dart #sharedpreferences
Вопрос:
При первой выборке данных из общих настроек я получаю эту ошибку: Необработанное исключение: ошибка NoSuchMethodError: средство получения ‘length’ было вызвано с нулевым значением. Но после горячей перезагрузки я получаю данные как обычно.
Извлечение данных с экрана панели мониторинга
loadSharedPrefs() async {
var decodedData = await sharedPref.read("details");
signInItem = SignInItem.fromJson(decodedData);
setState(() {});
}
Сохранение данных на экране входа
await FirebaseAuth.instance
.signInWithCredential(_phoneAuthCredential)
.then((AuthResult authRes) {
Navigator.pop(context);
Flushbar(
message: "Verified!!",
duration: Duration(seconds: 2),
)..show(context);
sharedPref.save("details", signInItem);
Navigator.popAndPushNamed(context, DashboardScreen.id);
});
Класс модели
class SignInItem {
String phoneNumber;
String schoolCode;
String schoolReference;
Map<String, dynamic> teacherData;
String error;
SignInItem.fromJson(Map<String, dynamic> json)
: phoneNumber = json['phoneNumber'],
schoolCode = json['schoolCode'],
schoolReference = json['schoolReference'],
teacherData = json['teacherData'],
error = json['error'];
Map<String, dynamic> toJson() => {
'phoneNumber': phoneNumber,
'schoolCode': schoolCode,
'schoolReference': schoolReference,
'teacherData': teacherData,
'error': error,
};
SignInItem(
{this.phoneNumber,
this.schoolCode,
this.schoolReference,
this.teacherData,
this.error});
}
Вспомогательный класс общих настроек
class SharedPref {
read(String key) async {
final prefs = await SharedPreferences.getInstance();
return json.decode(prefs.getString(key));
}
save(String key, SignInItem signInItem) async {
final prefs = await SharedPreferences.getInstance();
prefs.setString(key, json.encode(signInItem.toJson()));
}
}
Подробная трассировка стека
[ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: NoSuchMethodError: The getter 'length' was called on null.
E/flutter (19241): Receiver: null
E/flutter (19241): Tried calling: length
E/flutter (19241): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
E/flutter (19241): #1 _parseJson (dart:convert-patch/convert_patch.dart:39:28)
E/flutter (19241): #2 JsonDecoder.convert (dart:convert/json.dart:505:36)
E/flutter (19241): #3 JsonCodec.decode (dart:convert/json.dart:156:41)
E/flutter (19241): #4 SharedPref.read (package:teacher_app/constants.dart:156:17)
E/flutter (19241): <asynchronous suspension>
E/flutter (19241): #5 _DashboardScreenState.loadSharedPrefs (package:teacher_app/screens/dashboard_screen.dart:33:40)
E/flutter (19241): #6 _DashboardScreenState.initState (package:teacher_app/screens/dashboard_screen.dart:49:5)
E/flutter (19241): #7 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4684:58)
E/flutter (19241): #8 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4520:5)
E/flutter (19241): #9 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3490:14)
E/flutter (19241): #10 Element.updateChild (package:flutter/src/widgets/framework.dart:3258:18)
E/flutter (19241): #11 SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5874:14)
E/flutter (19241): #12 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3490:14)
E/flutter (19241): #13 Element.updateChild (package:flutter/src/widgets/framework.dart:3258:18)
E/flutter (19241): #14 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4571:16)
E/flutter (19241): #15 Element.rebuild (package:flutter/src/widgets/framework.dart:4262:5)
E/flutter (19241): #16 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4525:5)
E/flutter (19241): #17 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4520:5)
E/flutter (19241): #18 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3490:14)
E/flutter (19241): #19 Element.updateChild (package:flutter/src/widgets/framework.dart:3258:18)
E/flutter (19241): #20 SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5874:14)
E/flutter (19241): #21 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3490:14)
E/flutter (19241): #22 Element.updateChild (package:flutter/src/widgets/framework.dart:3258:18)
E/flutter (19241): #23 SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5874:14)
E/flutter (19241): #24 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3490:14)
E/flutter (19241): #25 Element.updateChild (package:flutter/src/widgets/framework.dart:3258:18)
E/flutter (19241): #26 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4571:16)
E/flutter (19241): #27 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4719:11)
E/flutter (19241): #28 Element.rebuild (package:flutter/src/widgets/framework.dart:4262:5)
E/flutter (19241): #29 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4525:5)
E/flutter (19241): #30 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4710:11)
E/flutter (19241): #31 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4520:5)
E/flutter (19241): #32 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3490:14)
E/flutter (19241): #33 Element.updateChild (package:flutter/src/widgets/framework.dart:3258:18)
E/flutter (19241): #34 SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5874:14)
E/flutter (19241): #35 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3490:14)
E/flutter (19241): #36 Element.updateChild (package:flutter/src/widgets/framework.dart:3258:18)
E/flutter (19241): #37 SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5874:14)
E/flutter (19241): #38 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3490:14)
E/flutter (19241): #39 Element.updateChild (package:flutter/src/widgets/framework.dart:3258:18)
E/flutter (19241): #40 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4571:16)
E/flutter (19241): #41 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4719:11)
E/flutter (19241): #42 Element.rebuild (package:flutter/src/widgets/framework.dart:4262:5)
E/flutter (19241): #43 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4525:5)
E/flutter (19241): #44 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4710:11)
E/flutter (19241): #45 ComponentElement.mount (package:flutter/src/widgets/framework.dart
Ответ №1:
Общие настройки требуют времени для сохранения деталей, и я извлекал данные перед их сохранением. Вот почему я получал null.
Я решил это, отложив переход к экрану панели мониторинга с помощью этого:
await FirebaseAuth.instance
.signInWithCredential(_phoneAuthCredential)
.then((AuthResult authRes) {
sharedPref.save("details", signInItem);
Timer(Duration(seconds: 2), () {
Navigator.pop(context);
Navigator.popAndPushNamed(context, DashboardScreen.id);
});
});
Но спасибо @TheSohan за то, что сообщил мне, где я получал null.
Ответ №2:
В методе чтения класса SharedPref; используйте проверку на нуль перед декодированием данных. Пример:
class SharedPref {
read(String key) async {
final prefs = await SharedPreferences.getInstance();
string data = prefs.getString(key)
if(data){
return json.decode(prefs.getString(key));
}
return data
}
аналогичным образом, добавьте проверку null в метод loadSharedPrefs.
loadSharedPrefs() async {
var decodedData = await sharedPref.read("details");
if(decodedData){
signInItem = SignInItem.fromJson(decodedData);
}
setState(() {});
}
Комментарии:
1. Зачем нужна проверка null? Мне нужны эти данные, и я уверен, что получу их, но не могу понять, почему я получаю null в первый раз?
2. Хорошей практикой кодирования является вставка проверки null в таких случаях