我使用以下代码处理从json.decode()
函数生成的地图:
for (var i = 0; i < data[0]["conversation"].length; i++) {
print(data[0]["conversation"][i]["conversationID"]);
print(data[0]["conversation"][i]["startDate"]);
print(data[0]["conversation"][i]["lastActivity"]);
print(data[0]["conversation"][i]["messageCount"]);
for (var j = 0; j < int.parse( data[0]["conversation"][i]["messageCount"] ); j++) {
print(data[0]["conversation"][i]["messages"]["message"][j]);
}
print("\n");
}
在最外部的“ for”中一切正常,问题出在内部的“ for”中,在尝试访问值时出现错误:
for (var j = 0; j < int.parse( data[0]["conversation"][i]["messageCount"] ); j++) {
print(data[0]["conversation"][i]["messages"]["message"][j]["body"]);
}
这是错误:
E/flutter ( 1650): [ERROR:flutter/shell/common/shell.cc(181)] Dart Error: Unhandled exception:
E/flutter ( 1650): NoSuchMethodError: The method '[]' was called on null.
E/flutter ( 1650): Receiver: null
E/flutter ( 1650): Tried calling: []("body")
E/flutter ( 1650): #0 Object.noSuchMethod (dart:core/runtime/libobject_patch.dart:50:5)
E/flutter ( 1650): #1 ChatScreenState.obtenerMensajesArchivados (file:///home/fenrir/Documents/api/lib/chat/chat_page.dart:115:67)
E/flutter ( 1650): <asynchronous suspension>
E/flutter ( 1650): #2 ChatScreenState.initState.<anonymous closure> (file:///home/fenrir/Documents/api/lib/chat/chat_page.dart:157:7)
E/flutter ( 1650): #3 _RootZone.runUnary (dart:async/zone.dart:1379:54)
E/flutter ( 1650): #4 _FutureListener.handleValue (dart:async/future_impl.dart:129:18)
E/flutter ( 1650): #5 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:642:45)
E/flutter ( 1650): #6 Future._propagateToListeners (dart:async/future_impl.dart:671:32)
E/flutter ( 1650): #7 Future._complete (dart:async/future_impl.dart:476:7)
E/flutter ( 1650): #8 _SyncCompleter.complete (dart:async/future_impl.dart:51:12)
E/flutter ( 1650): #9 _AsyncAwaitCompleter.complete.<anonymous closure> (dart:async/runtime/libasync_patch.dart:33:20)
E/flutter ( 1650): #10 _microtaskLoop (dart:async/schedule_microtask.dart:41:21)
E/flutter ( 1650): #11 _startMicrotaskLoop (dart:async/schedule_microtask.dart:50:5)
的示例
data[0]["conversation"][i]["messages"]["message"][j] :
{conversationID: 230, from: 123@localhost, to: 456@localhost, sentDate: 2018-10-18T12:48:05.039Z, body: aloha, roomEvent: false}
print(data[0]["conversation"][i]["messages"]["message"][j].runtimeType); return:
_InternalLinkedHashMap<String, dynamic>
我不知道错误可能是什么,因为在第一个“ for”中它对我有用,但是在第二个中,它不是:(
答案 0 :(得分:1)
错误是在["body"]
上使用null
,因此对于 some j
值,data[0]["conversation"][i]["messages"]["message"][j]
必须为null
。 / p>
尝试查找引发此问题的i
和j
,然后检查“消息”是否列出了预期的元素数量,并且没有一个是null
。