flutter 参数类型“Sound”不能分配给参数类型“Map〈String,dynamic>”

mjqavswn  于 2023-02-25  发布在  Flutter
关注(0)|答案(1)|浏览(98)

大家好我有这个问题与flutter当我是traying转换json到dart列表我有这个类

class Sound {
final int id;
final String name;
final String about;
final List<String> album;

Sound({required this.id,required this.name , required this.about , required this.album});

factory Sound.fromJson(Map<String, dynamic> json) {
return Sound (
id: json["id"],
name: json["name"],
about: json["about"],
album: List<String>.from(json["album"]),
);
}
}

这是WebServices类

import 'package:dio/dio.dart';
import 'package:sound/data/model/model.dart';

import '../../constants/strings.dart';

class SoundsWebServices {
  late Dio dio;

  SoundsWebServices() {
    BaseOptions options = BaseOptions(
      baseUrl: "http://10.0.2.2:8000/list/",
      receiveDataWhenStatusError: true,
      connectTimeout: const Duration(seconds: 60), // 60 seconds,
      receiveTimeout: const Duration(seconds: 60),
    );

    dio = Dio(options);
  }
  Future<List<Sound>> getAllSounds() async {
    try {
      Response response = await dio.get('Album/');
      print(response.data.toString());

      return response.data ;
    } catch (e) {
      print("aniba");
      print(e.toString());
      return [];
    }
  }
}

最后是存储库

import '../model/model.dart';
import '../web_services/sounds_wev_services.dart';

class SoundsRepository {
  final SoundsWebServices soundsWebServices;

  SoundsRepository(this.soundsWebServices);

  Future<List<Sound>> getAllSounds() async {
    final sounds = await soundsWebServices.getAllSounds();
    return sounds.map((sound) => Sound.fromJson(sound)).toList();
  }
}

问题出在类SoundsRepository上它显示了这个错误参数类型'Sound'不能赋值给参数类型'Map〈String,dynamic〉'.
我在互联网上搜索,但我没有找到解决方案

ycl3bljg

ycl3bljg1#

您的SoundWebService.getAllSounds方法已将数据作为**Future**返回,因此无需在此处执行Map。

class SoundsRepository {
  final SoundsWebServices soundsWebServices;

  SoundsRepository(this.soundsWebServices);

  Future<List<Sound>> getAllSounds() async {
    return await soundsWebServices.getAllSounds();
  }
}

但是您必须在SoundWebService.getAllSounds方法内部进行Map,这取决于response.data的外观。

相关问题