0

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'] ?? '',

    );
  }
}
2
  • can you add some sample data and the ui that you are expecting to render on the screen. Commented Dec 19, 2020 at 16:56
  • I just added more code, I'm new enough to flutter that I'm not sure what you mean by the UI, unless you're just talking about a mock up. The structure is, snapshot.data.fields contains a list object of fields. I'm just specifically not sure how to start looping through that list object of fields for display, any display really. Commented Dec 19, 2020 at 17:49

2 Answers 2

1

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)

Sign up to request clarification or add additional context in comments.

Comments

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

3 Comments

While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review
While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.
@Kevin What link?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.