繁体   English   中英

如何修复以下错误:键入“列表<dynamic> ' 不是 'Map 类型的子类型<dynamic, dynamic> '?</dynamic,></dynamic>

[英]How can I fix the following error: type 'List<dynamic>' is not a subtype of type 'Map<dynamic, dynamic>'?

这是导致问题的文件:

import 'package:http/http.dart' as http;
import './question_model.dart';
import 'dart:convert';

class DBconnect {
  final url = Uri.parse(
      'https://quizzapp-f2354-default-rtdb.firebaseio.com/questions.json');
  Future<List<Question>> fetchQuestions() async {
    return http.get(url).then((response) {
      var data = json.decode(response.body) as Map<String, dynamic>;
      List<Question> newQuestions = [];
      data.forEach((key, value) {
        var newQuestion = Question(
          id: key,
          title: value['title'],
          options: Map.castFrom(value['options']),
        );
        newQuestions.add(newQuestion);
      });
      return newQuestions;
    });
  }
}

这是我加载到 firebase 实时数据库中的 JSON 文件:

{
    "questions": {
        "first": {
            "title": "Who is the best player in the world?",
            "options": {
                "messi": "true",
                "ronaldo": "false",
                "haaland": "false",
                "mbappe": "false"
            }
        },
        "second": {
            "title": "2 + 2 = ?",
            "options": {
                "1": "false",
                "2": "false",
                "3": "false",
                "4": "true"
            }
        }
    }
}

我尝试运行应用程序并期待问题加载到应用程序中。

/// 出现问题是因为 API 没有正常工作,用这个替换你的代码并尝试

class DBconnect {
      final url = Uri.parse('https://quizzapp-f2354-default-rtdb.firebaseio.com/questions.json');

  Future<List<Question>> fetchQuestions() async {
    return http.get(url).then((http.Response? response) {
      if (response?.statusCode == 200 || response?.statusCode == 201) {
        var data = json.decode(response!.body) as Map<String, dynamic>;
        List<Question> newQuestions = [];
        data.forEach((key, value) {
          var newQuestion = Question(
            id: key,
            title: value['title'],
            options: Map.castFrom(value['options']),
          );
          newQuestions.add(newQuestion);
        });
        return newQuestions;
      } else {
        return [];
      }
    });
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM