[英]Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'Map<dynamic, dynamic>' --Flutter - RealtimeDatabase -
I am trying to get the information of the latest added to the database.我正在尝试获取最新添加到数据库的信息。 I have seen on the internet that one way to get the information is this,
我在互联网上看到获取信息的一种方法是,
await _lastKeyRef.once().then((DataSnapshot snapshot) {
if (snapshot.value != null) {
Map<dynamic, dynamic> _values = snapshot.value;
_values.forEach((key, value) {
.... code ...
});
{
{
but it gives me an error.但它给了我一个错误。
I leave the code to see if someone can help me.我留下代码,看看是否有人可以帮助我。
Picture of Realtime Database structure实时数据库结构图
final String _uid = SupermarketApp.sharedPreferences.getString(SupermarketApp.userUID);
final _turnRef = FirebaseDatabase.instance
.reference()
.child('cod')
.child('service');
Future<void> createTurn() async {
var _lastKeyRef = _turnRef.orderByKey().limitToLast(1);
DateTime _timeNow = new DateTime.now();
int _lastNumber;
int _setNumber;
await _lastKeyRef.once().then((DataSnapshot snapshot) {
if (snapshot.value != null) {
Map<dynamic, dynamic> _values = snapshot.value;
_values.forEach((key, value) {
_lastNumber = int.parse(key) + 1;
_setNumber = value['num'] + 1;
});
if (_setNumber > 99) _setNumber = 1;
_turnRef.child(_lastNumber.toString()).set(
{'app': true, 'user_id': _uid, 'date': _timeNow.toString(), 'num': _setNumber});
} else {
_turnRef
.child('1')
.set({'app': true, 'user_id': _uid, 'date': _timeNow.toString(), 'num': 1});
}
});
}
Thank you.谢谢你。
--Edit-- - 编辑 -
The code is good.代码很好。 The Exeption was due to having a "1" as a key in realtime database.
Exeption 是由于在实时数据库中将“1”作为键。 I dont know why, but i change the key name and it works.
我不知道为什么,但是我更改了密钥名称并且它可以工作。
The error is because snapshot.value
returns a List but you're reading it as a Map
.该错误是因为
snapshot.value
返回一个 List 但您将其读取为Map
。
Updating the code to the one below should fix this:将代码更新到以下代码应该可以解决此问题:
List<dynamic> _values = snapshot.value;
_values.forEach((element) {
int key = _values.indexOf(element)l
_lastNumber = int.parse(key) + 1;
_setNumber = element['num'] + 1;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.