如何在颤振中显示列表

时间:2020-12-19 16:34:47

标签: flutter dart

我正在构建一个 Flutter 应用程序,但我不确定如何与其他元素一起显示我的列表。

我将从我的代码开始

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),
                                    ),
  
                                  )
                                ])
                              ],
                            ),
                          );
                        }
                    }
                  }),
            )
        )
    );
  }

}

我迷路的地方是,snapshot.data.fields 是一个字段列表。我不知道如何遍历此列表以显示每个字段。

每个字段项都有一个标签和一个值。

有人可以告诉我如何使用现有元素将其添加到此小部件的底部吗?我的问题更多是关于颤振,如果你能让我指出正确的方向,那么我想我可以完成它。

编辑:我正在添加车辆和字段的期货,以便您可以看到结构

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 个答案:

答案 0 :(得分:1)

看看 ListView.builder 方法。显然,您将需要整个 List。那么你将如何获得它呢?通过返回 Future <List<Vehicle>> 的函数获取它。另请查看 online docs

并在您的构建方法中包括:

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));
            });
      }
  }

修改每个条目的 Widget _taskWidget () {/*...*/}。 (您的列表界面)

答案 1 :(得分:0)

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