Home > Blockchain >  How to solve the problem with types in flutter?
How to solve the problem with types in flutter?

Time:11-19

I have an array of elements that come from api and I get and error from api =>

The operator '[]' isn't defined for the type of 'Country'

Response from api looks like this:

{"success":true,"list":[{"id":2,"createdAt":"2022-11-11T15:25:31.680Z","updatedAt":"2022-11-11T15:25:31.680Z","name":"Afghanistan"}]}

This is the type of an element inside list:

class Country {
  final int id;
  final String createdAt;
  final String updatedAt;
  final String name;

  const Country({
    required this.id,
    required this.createdAt,
    required this.updatedAt,
    required this.name
  });
}

This is my widget:

class MyWidget extends StatefulWidget {
  const MyWidget({super.key});

  @override
  State<MyWidget> createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {

  List<Country> countries = [];

  Future<void> getCountries() async {
    try {
      final response = await _apiService.getCountries();
      countries = response['list']; // [{"id": 2, "createdAt:""...}]
    } catch (e) {
      log(e.toString());
      rethrow;
    }
  }

  @override
  void initState() {
    getCountries();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

And if I try to call this, IDE lights me this error in country['name'] =>

final List countriesWithNames = countries.map((country) => country['name']).toList();

Or when I try to get an element from the list, like this => countries[index]['name']

CodePudding user response:

response['list'] returns list of map.You need to convert into model class.

You can use this model class

class Country {
  final int id;
  final String createdAt;
  final String updatedAt;
  final String name;

  const Country({
    required this.id,
    required this.createdAt,
    required this.updatedAt,
    required this.name,
  });

  Map<String, dynamic> toMap() {
    final result = <String, dynamic>{};

    result.addAll({'id': id});
    result.addAll({'createdAt': createdAt});
    result.addAll({'updatedAt': updatedAt});
    result.addAll({'name': name});

    return result;
  }

  factory Country.fromMap(Map<String, dynamic> map) {
    return Country(
      id: map['id']?.toInt() ?? 0,
      createdAt: map['createdAt'] ?? '',
      updatedAt: map['updatedAt'] ?? '',
      name: map['name'] ?? '',
    );
  }

  String toJson() => json.encode(toMap());

  factory Country.fromJson(String source) =>
      Country.fromMap(json.decode(source));
}

And getting from local json string

final data = response["list"] as List?;
List<Country> countries =
    data?.map((e) => Country.fromMap(e)).toList() ?? [];

print(countries);
  • Related