-1

I am trying to convert JSON to a dart list.

I have this class

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"]),
    );
  }
}

And this is the WebServices class

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 [];
    }
  }
}

And finally this the Repository

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();
  }
}
 

The problem is with the class SoundsRepository. I get this error:

The argument type Sound can't be assigned to the parameter type Map<String, dynamic>.

double-beep
  • 5,031
  • 17
  • 33
  • 41
ANNABA Naruto
  • 11
  • 1
  • 3

1 Answers1

0

Yours SoundWebService.getAllSounds method already returns the data as a Future<List> so you do not need to do a mapping here.

class SoundsRepository {
  final SoundsWebServices soundsWebServices;

  SoundsRepository(this.soundsWebServices);

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

But you have to do the mapping inside the SoundWebService.getAllSounds methods, depending on how the response.data looks like.

Vladimir Gadzhov
  • 273
  • 2
  • 10