John Sly
John Sly

Reputation: 769

How can I display a list in flutter

I'm building a flutter app but I'm not sure how to display my list along with other elements.

I'll start with my code

class showVehicle extends StatelessWidget {
  final Future<Vehicle> vehicle;

  showVehicle({Key key, this.vehicle}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return SafeArea(
        child: Scaffold(
            body: Center(
              child: FutureBuilder<Vehicle>(
                  future: vehicle,
                  builder: (context, snapshot) {
                    switch (snapshot.connectionState) {
                      case ConnectionState.none:
                        return Text('none');
                      case ConnectionState.waiting:
                        return Center(child: CircularProgressIndicator());
                      case ConnectionState.active:
                        return Text('');
                      case ConnectionState.done:
                        if (snapshot.hasError) {
                          return Text(
                            '${snapshot.error}',
                            style: TextStyle(color: Colors.red),
                          );
                        } else {
                          return InkWell(
                            child: Column(
                              children: <Widget>[
                                Stack(children: <Widget>[
                                  FadeInImage.memoryNetwork(
                                    placeholder: kTransparentImage,
                                    image:
                                    '${snapshot.data.defImage}',
                                    height: 250,
                                    fit: BoxFit.cover,
                                  ),
                                  Container(
                                    padding: EdgeInsets.all(5.0),
                                    margin:
                                    EdgeInsets.fromLTRB(0.0, 5.0, 0.0, 5.0),
                                    //width: 250,
                                    height: 250,
                                    alignment: Alignment.bottomCenter,
                                    decoration: BoxDecoration(
                                      gradient: LinearGradient(
                                        begin: Alignment.topCenter,
                                        end: Alignment.bottomCenter,
                                        colors: <Color>[
                                          Colors.black.withAlpha(0),
                                          Colors.black12,
                                          Colors.black87
                                        ],
                                      ),
                                    ),
                                    child: Text(
                                      '${snapshot.data.brand} ${snapshot.data.model}',
                                      style: TextStyle(
                                          color: Colors.white, fontSize: 20.0),
                                    ),
  
                                  )
                                ])
                              ],
                            ),
                          );
                        }
                    }
                  }),
            )
        )
    );
  }

}

Where I'm lost is, snapshot.data.fields is a List of fields. I don't know how to loop through this list to display each field.

Each field item has a label and a value.

Can someone show me how I can add that to the bottom of this widget with the existing elements already? My issue is more on flutter, if you can get me pointed in the right direction, then I think I can finish it.

EDIT: I'm adding the futures for the vehicle and fields so you can see the structure

Future<Vehicle> fetchVehicle(String id) async {
  final response = await http.get(globals.urlPath + 'vehicles/'+id+'/json/');

  if (response.statusCode == 200) {
    // If the call to the server was successful, parse the JSON.
    return Vehicle.fromJson(convert.jsonDecode(response.body));
  } else {
    // If that call was not successful, throw an error.
    throw Exception('Failed to load post');
  }
}

class Vehicle {
  final String id;
  final String title;
  final String url;
  final String defImage;
  final String brand;
  final String model;
  final List<Fields> fields;

  Vehicle({this.id, this.title, this.url, this.defImage, this.brand, this.model, this.fields});

  factory Vehicle.fromJson(Map<String, dynamic> json) {

    List<Fields> tempFields = [];
    if(json['[fields]'] != null) {
      for (int i = 0; i < json['[fields]'].length; i++) {
        //print("Image: " + i.toString() + " of " + json['images'].length.toString());
        Fields field = Fields.fromJson(json['fields'][i]);
        tempFields.add(field);
      }
    }

    //"Vehicle Type"
    var brand = "";
    var model = "";

    if (json['content'] != null && json['content']['[fields]'] != null){ // we have our fields
      json['content']['[fields]'].forEach((field) {
        Map<String, dynamic> params = field;
        if(field['[label]'] == "Brand"){
          //assign this to something
          brand = field['[fieldFormattedVal]'];
        }
        if(field['[label]'] == "Model"){
          //assign this to something
          model = field['[fieldFormattedVal]'];
        }
       });
    }

    return Vehicle(
      id: json['id'] ?? json['dataObj']['id'],
      title: json['[title]'] ?? json['content']['[fields]'][0]['[fieldFormattedVal]'] ?? '',
      url: json['[url]'] ?? '',
      defImage: json['[fileName]'] ?? json['content']['[images]'][0]['[fileName]'] ?? '',
      brand: brand ?? '',
      model: model ?? '',
      fields: tempFields, //field.fromJson(json['[fields]']) ?? '',
    );
  }
}

class Fields {
  final String conditions;
  final String label;
  final String name;
  final String rawval;
  final String val;

  Fields({this.conditions, this.label, this.name, this.rawval, this.val});

  factory Fields.fromJson(Map<String, dynamic> json) {
    return Fields(
      conditions: json['conditions'] ?? '',
      label: json['label'] ?? '',
      name: json['name'] ?? '',
      rawval: json['fieldRawVal'] ?? '',
      val: json['fieldFormattedVal'] ?? '',

    );
  }
}

Upvotes: 0

Views: 2436

Answers (2)

Onur Ural
Onur Ural

Reputation: 129

case ConnectionState.active:
    return Text(snapshot.data[title]);    // you can reach any field 

Upvotes: 0

Phill Alexakis
Phill Alexakis

Reputation: 1499

Take a look at the ListView.builder method. You will obviously need the whole List for that. So how would you obtain it? Get it through a function that returns Future <List<Vehicle>>. Also take a look at the online docs.

and in your build method include:

List<Vehicle> YourLocalList=[];

 @override
  Widget build(BuildContext context) {
   final Future<List<Vehicle>> future = //get in from your function
   return FutureBuilder(future: future, builder: (BuildContext context, snapshot) {
      
      print('${snapshot.data}'); //your list

      if(snapshot.hasData&&snapshot.data.length>=1) {
        YourLocalList = snapshot.data;
      
        return ListView.builder(
            padding: const EdgeInsets.all(8),
            itemCount: (YourLocalList.length),
            itemBuilder: (BuildContext context, int index) {
              return Container(
                  margin: EdgeInsets.only(top: 10, bottom: 10),
                  child: _taskWidget(index));
            });
      }
  }

Modify the Widget _taskWidget () {/*...*/} for each entry. (your list UI)

Upvotes: 1

Related Questions