簡體   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