简体   繁体   中英

Flutter convert JSON stream List into Map object

I am attempting to convert the JSON results of a Google Places API call to fit my Restaurant object, however, being new to Flutter I seem to be having issues. My results are put into a List but as you can see my Restaurant class expects a Map.

Here is my Restaurant class

class Restaurant{
  final String id;
  final String name;
  final GeoPoint location;
  final String image;

  const Restaurant({
    this.id,
    this.name,
    this.location,
    this.image,
  });

  Restaurant.fromMap(Map<String, dynamic> data, String id)
    : this(
        id: id,
        name: data['name'],
        location: data['location'],
        image: data['image'],
  );

}

The relevant part of my body:

Expanded(
              child: new FutureBuilder(
                future: _updateRestaurantsNearby(),
                builder: (BuildContext context, AsyncSnapshot snapshot) {
                  if (snapshot.connectionState == ConnectionState.none &&
                      snapshot.hasData == null) {
                    return Container();
                  }
                  if (!snapshot.hasData) return _buildLoadingIndicator();
                  return ListView.builder(
                    itemCount: snapshot.data.length,
                    itemBuilder: (BuildContext context, int index) {
                      return new RestaurantCard(
                        restaurant: Restaurant.fromMap(
                            snapshot.data[index], snapshot.data[index].id),
                      );

And finally my class for handling JSON data. I am using the google_maps_webservice package:

Future _updateRestaurantsNearby() async {
    PlacesSearchResponse response = await places.searchNearbyWithRadius(
      new Location(lat, long),
      radius,
    );

    if (response.hasNoResults) {
      print("No results");
      return null;
    }

    var nearbyRestaurants;
    var results = response.results;

    results.forEach((f) {
      Restaurant restaurant = Restaurant(
          id: f.id,
          name: f.name,
          location: GeoPoint(f.geometry.location.lat, f.geometry.location.lng),
          image: null);
      nearbyRestaurants.update(restaurant);
      //print(nearbyRestaurants.length);
    });
    return nearbyRestaurants;
  }

I would like to convert the data in the loop above to a Map instead of as a List so I can use them in the ListView builder, just not sure how to achieve that.

If the response by the http request returns a valid format, you can cast as Map<String, dynamic> on the value that you're passing on Restaurant.fromMap() . This lets the method know the data type that's being passed so it can be parsed.

Restaurant.fromMap(snapshot.data[index] as Map<String, dynamic>, 
    snapshot.data[index].id)

in class handle json you can try

import 'dart:convert';
Future<List<Model>> callSomething() async {
  /// you handle
  final response = await http.get(
      Uri.parse("uri"),
      headers: {"Accept": "application/json"});
  if (response.statusCode == 200) {

    // convert reponse body to json
    List<dynamic> body = json.decode(response.body);
    // convert json to objects model
    List<Model> data =
        body.map((dynamic item) => Model.fromJson(item)).toList();
    return data;
  } else {
    throw Exception("Faid to load data");
  }
}

you should use Cusom model in dart for Model and if will return for you Objects Model, after use

FutureBuilder(future:callSomething(),
...
)

goodluck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM