提问者:小点点

获取此持续错误。List<动态>不是Map<String,动态>类型的子类型


这是我的模特课

import 'dart:convert';

Streams streamsFromJson(String str) => Streams.fromJson(json.decode(str));

String streamsToJson(Streams data) => json.encode(data.toJson());

class Streams {
 Streams({
   this. Title,
   this. Stream,
   this. Description,
   this.author,
   this.availability,
 });

 String? title;
 String? stream;
String? description;
 String? author;
 bool? availability;

 factory Streams.fromJson(Map<String, dynamic> json) => Streams(
       title: json["title"],
       stream: json["stream"],
       description: json["description"],
       author: json["author"],
       availability: json["availability"],
     );

 Map<String, dynamic> toJson() => {
      "title": title,
      "stream": stream,
      "description": description,
      "author": author,
      "availability": availability,
    };

}

这就是我获取数据的方式

class RetrieveStreams {
static var client = http.Client();
ProjectApis projectApis = ProjectApis();

static Future<Streams> fetchStreams() async {
  final response = await client. Get(
    Uri.parse(ProjectApis.streamsUrl),
  );
  if (response.statusCode == HttpStatus.ok) {
    // Call is successful 
    var jsonString = response. Body;
    return streamsFromJson(jsonString);
  } else {
    // If that call was not successful, throw an error.
    Get.snackbar(
      'Error',
      'Failed to load streams',
       backgroundColor: Colors.red,
      colorText: Colors.white,
     );
     throw Exception('');
    }
  }
}

这是我使用getx的控制器类

lass StreamsController extends GetxController {
 var streamList = <Streams>[].obs;

 void getStreams() async {
   var streamVariable = await RetrieveStreams.fetchStreams();
   streamList.value = streamVariable as List<Streams>;
 }

    @override
    void onInit() {
      getStreams();
   super.onInit();
  }
}

我在这个文本小部件中显示数据

Text(
   _streamsController.streamList
    .map((element) => element. Title)
     .toList()[index]
     .toString(),
      style: TextStyle(
      color: ProjectColors.black,
    ),
 ),

我已经仔细阅读了这里的输入链接描述,但它似乎并不能解决我的问题。

错误似乎表明我从endpoint接收的数据是列表的形式,而我使用的是地图,这表明数据不匹配。我似乎无法理解这个错误


共1个答案

匿名用户

看起来API返回的是一个数组而不是Streams对象。假设它是一个Streams对象的数组,使用以下函数对该数组进行编码/解码:

List<Streams> streamsListFromJson(String str) =>
    (json.decode(str) as List<dynamic>)
        .map((s) => Streams.fromJson(s))
        .toList();

String streamsListToJson(List<Streams> data) =>
    json.encode(data.map((s) => s.toJson()).toList());