Home > Mobile >  Flutter - Can´t iterate model values
Flutter - Can´t iterate model values

Time:04-02

In Flutter i have this model

class UserModel {
  final int id;
  final String name;
  final String email;
  final String language;
  final String city;
  final double latitude;
  final double longitude;

  UserModel(
      {required this.id,
      required this.name,
      required this.email,
      required this.language,
      required this.city,
      required this.latitude,
      required this.longitude});

  factory UserModel.fromJson(Map<String, dynamic> json) {
    return UserModel(
      id: json['id'] ?? 0,
      name: json['name'],
      email: json['email'],
      language: json['language'],
      city: json['city'],
      latitude: json['latitude'],
      longitude: json['longitude'],
    );
  }
}

Then in service i hace two functions

  Future getAllSimple() async {
    var url = Uri.parse('http://10.0.2.2:80/users/all');
    var response = await http.get(url);
    if (response.statusCode == 200) {
      return jsonDecode(response.body);
    } else {
      throw Exception('Error: ${response.statusCode}.');
    }
  }

  Future<UserModel> getAll() async {
    var url = Uri.parse('http://10.0.2.2:80/users/all');
    var response = await http.get(url);
    if (response.statusCode == 200) {
      return UserModel.fromJson(jsonDecode(response.body));
    } else {
      throw Exception('Error: ${response.statusCode}.');
    }
  }

In controller this works

  Future getMarkers() async {
    UserService().getAllSimple().then((value) { // Here
      setState(() {
        value.forEach((key, element) {
          _markers.add(Marker(
            markerId: MarkerId(element['id']),
            position: LatLng(element['latitude'], element['longitude']),
            infoWindow: InfoWindow(
              title: element['name'],
            ),
            icon: BitmapDescriptor.defaultMarker,
          ));
        });
      });
    }).catchError((e) {
      debugPrint(e);
    });
  }

But if i try to use getAll i can't do foreach because is a model map. Anybody know how can i convert model to can do foreach over all values?

CodePudding user response:

According to user provided codes for controller, your api call will return list of json data. So you may follow these steps:

Create a json list data parser method

List<UserModel> usersFromJson(String body) =>
    List<UserModel>.from(jsonDecode(body).map((x) => UserModel.fromJson(x)));

Use usersFromJson method to return the List

Future<List<UserModel>> getAll() async {
    var url = Uri.parse('http://10.0.2.2:80/users/all');
    var response = await http.get(url);
    if (response.statusCode == 200) {
      return usersFromJson(response.body);
    } else {
      throw Exception('Error: ${response.statusCode}.');
    }
  }

Call the getMarkers() method and iterate the list of users

  Future getMarkers() async {
    UserService().getAll().then((value) { // Here

      if(value != null && value is List<UserModel>) {
        setState(() {
          for (var element in value) {
            _markers.add(Marker(
              markerId: MarkerId(element.id),
              position: LatLng(element.latitude, element.longitude),
              infoWindow: InfoWindow(
                title: element.name,
              ),
              icon: BitmapDescriptor.defaultMarker,
            ));
          }
        });
      } else {
        log("value is null or not List<UserModel>")
      }
    }).catchError((e) {
      debugPrint(e);
    });
  }
  • Related