我試圖在可用時將當前答案作為提示文本。但我收到了這個錯誤:NoSuchMethodError: The getter 'isNotEmpty' was called on null.
關于如何解決它的任何想法?
final Map<String, String> answers = {};
final Map<String, String> qst = {
"Everyone should read...": "",
"Two truths and a lie...": "",
"I can quote every line from...": "",
"If I didn't have to work I would...": "",
"People think I am...": "",
"Never have I ever...": "",
"Believe it or not, I...": "",
"I am amazing at...": "",
"My life as a movie...": "",
"My ultimate dinner party guest list...": "",
"The dorkiest thing about me is...": "",
"On the weekend you'll find me...": "",
};
Future<void> _write(Map<String, dynamic> map) async {
final directory = await getApplicationDocumentsDirectory();
final jsonStr = jsonEncode(map);
final file = File('${directory.path}/answers.txt');
await file.writeAsString(jsonStr);
}
List<Data> data = [];
@override
void initState() {
super.initState();
read();
}
Future<Map<String, dynamic>> read() async {
final directory = await getApplicationDocumentsDirectory();
final file = File('${directory.path}/answers.txt');
final jsonStr = await file.readAsString();
final raw = jsonDecode(jsonStr) as Map<String, dynamic>;
raw.forEach((key, value) {
data.add(Data(question: key, answer: value));
});
print(raw);
return raw;
}
@override
Widget build(
BuildContext context,
) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
for (var q in qst.keys) question(q),
SizedBox(
height: 50,
),
],
);
}
Widget question(String question) {
final myController = TextEditingController();
return Padding(
padding: const EdgeInsets.only(top: 15),
child: Stack(
children: [
Card(
elevation: 0,
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.only(bottom: 15, left: 10),
child: Text(
question,
style: TextStyle(
color: Colors.black,
fontSize: 18.0,
fontWeight: FontWeight.bold),
),
),
TextField(
onChanged: (String ansr) {
answers[question] = ansr;
},
onSubmitted: (String ansr) {
_write(answers);
},
controller: myController,
decoration: InputDecoration(
hintText: answers[question].isNotEmpty
? answers[question]
: "write something",
),
),
],
),
),
),
],
),
);
}
}
我應該使用一些狀態管理還是有其他方法可以做到這一點?{這是一個隨機文本,所以 stackoverflow 接受我的問題,因為它說我的問題主要是代碼,我需要添加更多細節}
uj5u.com熱心網友回復:
在 Dart 中,當從 map 中訪問值時,回傳的值可以是 Null 或存盤在 map 中的實際值。在您的情況下,在您嘗試訪問 的那一刻answers[question],沒有值 - 回傳 null 。然后,您嘗試呼叫isNotEmptyon null,您會收到錯誤訊息。
要解決此問題,請替換此:
decoration: InputDecoration(
hintText: answers[question].isNotEmpty
? answers[question]
: "write something",
),
有了這個:
decoration: InputDecoration(
hintText: answers[question]?.isNotEmpty ?? false
? answers[question]
: "write something",
),
在此示例中,如果answers[question]為 null,則該陳述句將屬于 false 條件,您的代碼不會中斷。
有關更多資訊,請檢查Dart 中的 null 安全性。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/434599.html
上一篇:如果值為null,則不執行賦值
