Flutter:从对象列表构建卡

时间:2018-11-17 14:51:43

标签: dart flutter android-cardview

我被困住了,我尝试从对象列表中创建卡片,这是我尝试过的事情:

class Product {
   final String id;

   Product({this.id});

   //we create a factory method to deserialize the json
   factory Product.fromJson(Map<String, dynamic> json) {
      return new Product(
         id: json['id'].toString()
      );
   }
 }

class ProductsList {
  final List<Product> products;

  ProductsList({this.products});

  factory ProductsList.fromJson(List<dynamic> parsedJson) {
     List<Product> products = new List<Product>();
     products = parsedJson.map((i)=>Product.fromJson(i)).toList();

     return new ProductsList(
        products: products,
     );
  }
}

Future<List<Product>> loadProducts() async {
   final response = await http.get('http://...');
   final jsonResponse = json.decode(response.body);
   final jsonData=jsonResponse['data'];
   ProductsList productsList = ProductsList.fromJson(jsonData);

   for (var p in productsList.products) {
      print(p.id); // OKAY, print in the console every id
   }
   return productsList.products;
}

Widget get _homeView {
  return new Column(
    children: <Widget>[
       new MaterialButton(
          child: const Text('products'),
          onPressed: () {
            loadProducts(); // OKAY, print in the console every id
          }),


      new FutureBuilder<Map>(
        future: loadProducts(),
        builder: (context, snapshot) {
           // in case loading products takes a while.
           if (!snapshot.hasData) return Center(child: CircularProgressIndicator());
           if (snapshot.hasData) {
              for (var p in snapshot.data) {
                print(p.id); //OKAY, print each id
              }
              return Column(children: snapshot.data.map(buildCard).toList()); // KO
          }
        },
      ),
    ]
  )
 }

结果:

当我单击按钮时,它将在控制台中打印产品ID的列表:好吧

但是我想展示所有产品,所以我尝试使用FutureBuilder,但我有点迷失了,快照数据始终是假的,知道吗?

这就是我得到的:

with snapshot.data.map(buildCard).toList():

enter image description here

with snapshot.data.map(buildCard())。toList():

enter image description here

0 个答案:

没有答案