如何解析类型'_InternalLinkedHashMap <dynamic,dynamic =“”>'不是'Map <string,dynamic =“”>类型的子类型

时间:2019-05-03 07:13:57

标签: firebase-realtime-database flutter

我正在尝试获取用户数据,但这样做时出现以下错误:

(env) acer@acer-Aspire-V3-472P:~/DjangoProject/Weather$ python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
May 03, 2019 - 06:48:01
Django version 2.2, using settings 'Weather.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Internal Server Error: /
Traceback (most recent call last):
  File "/home/acer/DjangoProject/env/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/home/acer/DjangoProject/env/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/acer/DjangoProject/env/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/acer/DjangoProject/Weather/weather_app/views.py", line 30, in index
    'temperature': city_weather['main']['temp'],
KeyError: 'main'
[03/May/2019 06:48:18] "GET / HTTP/1.1" 500 68977

我研究了类似问题的各种解决方案,并相应地更改了代码(例如:使用Exception: type '_InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'Map<String, dynamic> 而不是<String, dynamic>,但仍然看到此错误。

模型片段:

<dynamic, dynamic>

然后按以下方式获取此数据并在// Returns a Pro created from JSON factory Pro.fromJson(Map<String, dynamic> json) { Pro pro = Pro(); pro.uid = json['uid']; pro.email = json['email']; 中调用此方法:

initState()

如果我使用Future<Pro> _getPro() async { await userDatabaseReference.once().then((DataSnapshot snapshot) { Map<String, dynamic> values = snapshot.value; values["uid"] = snapshot.key; print(snapshot.key); Pro fetchedUser = Pro.fromJson(values); setState(() { this.pro = fetchedUser; }); }); } ,则在同一行出现错误;如果我使用Map<String, dynamic> values,则在以下地方出错: Map<dynamic, dynamic> values

因为,Pro fetchedUser = Pro.fromJson(values)的参数类型为Pro.fromJson(values),这与我以前声明Map<String, dynamic>的参数类型相同,但仍不确定为什么会引发错误。

1 个答案:

答案 0 :(得分:2)

请尝试以下操作,首先将值转换为Map.from(),然后将其与Pro模型的fromJson方法一起使用:

Future<Pro> _getPro() async {
    await userDatabaseReference.once().then((DataSnapshot snapshot) {
      Map<String, dynamic> values = snapshot.value;
      values["uid"] = snapshot.key;
      print(snapshot.key); 
      final mapJsonCategory = Map<String, dynamic>.from(values);
      Pro fetchedUser = Pro.fromJson(mapJsonCategory);
      setState(() {
        this.pro = fetchedUser;
      });
    });
  }