在Flutter中从列表访问List对象

oknrviil  于 2023-01-27  发布在  Flutter
关注(0)|答案(2)|浏览(136)

我有一个列表中的几个服务点的列表。
PointsOfServices中还有另一个名为Orders的对象。如何访问Orders对象以将其数据与PointsOfService数据一起使用?
谢谢

编辑:我希望能够使用此数据生成一个GridView,使我能够显示来自PointOfServices和Orders的数据。
在创建GridView时,我可以使用Future for this和FutureBuilder吗?

k3bvogb1

k3bvogb11#

您可以使用索引直接访问它

print(mainList[0].orders[0].id);

将打印第一个pointOfService的第一个订单的ID
注意:这里mainList是包含所有pointOfService的列表的名称,我假设您在每个顺序中都有id

jobtbby3

jobtbby32#

您的问题并不清楚您到底想要实现什么,但是要在list中访问list,您可以引用以下内容:

class PointOfService {
  final String name;
  final List<Order> orders;
  PointOfService({this.name, this.orders});
}

class Order {
  final String name;
  Order({this.name});
}

void main() {
  List<PointOfService> pointofServices = [
    PointOfService(
        name: "PointOfService 1",
        orders: [
          Order(name: "Order 1"),
          Order(name: "Order 2"),
        ]),
    PointOfService(
        name: "PointOfService 2",
        orders: [
          Order(name: "Order 3"),
          Order(name: "Order 4"),
        ])
  ];

  for (var pointOfService in pointofServices) {
    print("PointOfService name: ${pointOfService.name}");
    for (var order in pointOfService.orders) {
      print("Order name: ${order.name}");
    }
  }
}

这将输出

PointOfService name: PointOfService 1
Order name: Order 1
Order name: Order 2
PointOfService name: PointOfService 2
Order name: Order 3
Order name: Order 4

编辑

对于GridView,您可以执行以下操作:

FutureBuilder<List<PointOfService>>(
    future: < Your future here >
    builder: (context, snapshot) {
        if (snapshot.hasData) {
        return  GridView.builder(
            gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
                maxCrossAxisExtent: 200,
                childAspectRatio: 3 / 2,
                crossAxisSpacing: 20,
                mainAxisSpacing: 20),
            itemCount: snapshot.data.pointOfServices.length,
            itemBuilder: (context, index) {
                Order order = snapshot.data!.pointOfServices[index];
                return Column(
                       children:[
                           Text(order['name']),// You can access this way
                       );
              );
            }),
        } else {
        return Text("No data");
        }
    },
)

相关问题