【问题标题】:How to set the list of json data inside list in the Listview.builder in flutter?如何在颤动的Listview.builder中设置列表内的json数据列表?
【发布时间】:2020-06-11 09:46:41
【问题描述】:

我是新来的颤振。我已将我的 json 从 here 转换为 pojo。我的api在下面。我能够从 api 获取数据,但 Orderdata 中有 3 个食物项目,但我只能获得索引 0 的值,如下图所示: 我已实现如下:

    {
    "status": "success",
    "message": "Data Fetched",
    "data": {
        "list": [
            {
                "id": 174,
                "order_code": "mkjrovcjjrvra6t3vtgo58",
                "chef_id": 1,
                "user_id": 58,
                "order_status": 2,
                "status": 3,
                "order_datetime": "2020-02-27 10:25:28",
                "user_location_id": 1,
                "instruction": null,
                "price": 2020,
                "coupon_id": null,
                "use_coupon": 0,
                "discount": 0,
                "final_price": 2020,
                "vat_amt": 262.6,
                "delivery_charge_amt": 0,
                "payment_id": 1,
                "delivery_time": null,
                "delivery_user_id": null,
                "payment_status": 0,
                "payment_price": null,
                "payment_time": null,
                "reject_message": null,
                "created_at": "2020-02-27 10:25:28",
                "updated_at": "2020-02-27 10:25:48",
                "orderdata": [
                    {
                        "id": 203,
                        "order_code_id": 174,
                        "chef_id": 1,
                        "food_id": 17,
                        "user_id": 58,
                        "additional_info": null,
                        "food_qty": 1,
                        "instruction": null,
                        "price": 400,
                        "food": {
                            "id": 17,
                            "name": "Prawns Chilli",
                            "description": "<p>Seared&nbsp;prawns&nbsp;smothered in a spicy, sticky Asian sauce, these Asian&nbsp;Chilli&nbsp;Garlic&nbsp;Prawns&nbsp;will have you smacking your lips in utter satisfaction, feeling like you&rsquo;ve just dined at a fancy modern Thai restaurant.<wbr />&nbsp;</p>",
                            "ingredient_detail": "<p>2 tablespoons reduced sodium soy sauce, 2 tablespoons freshly squeezed lime juice, 2 tablespoons canola oil, divided, 3 cloves garlic, minced, 2 teaspoons chili powder, 1 teaspoon ground cumin, 1 teaspoon dried oregano, 1 1/2 pounds skirt steak, cut into 1/2-inch pieces, 12 mini flour tortillas, warmed, 3/4 cup diced red onion, 1/2 cup chopped fresh cilantro leaves, 1 lime, cut into wedges</p>",
                            "price": 500,
                            "discount_price": 400,
                            "ribbon_text": null,
                            "image": "1581750558-1576657695-prawn-chilli3jpg.jpg",
                            "banner_image": null,
                            "published_date": "2019-12-18",
                            "is_offer": 1
                        }
                    },
                    {
                        "id": 204,
                        "order_code_id": 174,
                        "chef_id": 1,
                        "food_id": 17,
                        "user_id": 58,
                        "additional_info": null,
                        "food_qty": 3,
                        "instruction": null,
                        "price": 400,
                        "food": {
                            "id": 17,
                            "name": "Prawns Chilli",
                            "description": "<p>Seared&nbsp;prawns&nbsp;smothered in a spicy, sticky Asian sauce, these Asian&nbsp;Chilli&nbsp;Garlic&nbsp;Prawns&nbsp;will have you smacking your lips in utter satisfaction, feeling like you&rsquo;ve just dined at a fancy modern Thai restaurant.<wbr />&nbsp;</p>",
                            "ingredient_detail": "<p>2 tablespoons reduced sodium soy sauce, 2 tablespoons freshly squeezed lime juice, 2 tablespoons canola oil, divided, 3 cloves garlic, minced, 2 teaspoons chili powder, 1 teaspoon ground cumin, 1 teaspoon dried oregano, 1 1/2 pounds skirt steak, cut into 1/2-inch pieces, 12 mini flour tortillas, warmed, 3/4 cup diced red onion, 1/2 cup chopped fresh cilantro leaves, 1 lime, cut into wedges</p>",
                            "price": 500,
                            "discount_price": 400,
                            "ribbon_text": null,
                            "image": "1581750558-1576657695-prawn-chilli3jpg.jpg",
                            "banner_image": null,
                            "published_date": "2019-12-18",
                            "is_offer": 1
                        }
                    },
                    {
                        "id": 205,
                        "order_code_id": 174,
                        "chef_id": 1,
                        "food_id": 4,
                        "user_id": 58,
                        "additional_info": null,
                        "food_qty": 3,
                        "instruction": null,
                        "price": 140,
                        "food": {
                            "id": 4,
                            "name": "Chili Momo",
                            "description": "<p>This juicy steamed momos are prepared from the ground water buffalo meat and are called \"Buff&nbsp;momo\". The wrappers are very thinly rolled and the filling is deliciously spicy and juicy, served along with tangy yellow chutney and classic spicy tomato sauce that compliments the&nbsp;taste&nbsp;of steamed momos.</p>",
                            "ingredient_detail": "<p>Tomato, Ground meat ,Flour, Chilli pepper, Garlic, Ginger, Scallion, Black pepper and Soy sauce</p>",
                            "price": 150,
                            "discount_price": 140,
                            "ribbon_text": null,
                            "image": "1580971029-c-momojfif.jfif",
                            "banner_image": null,
                            "published_date": "2019-11-18",
                            "is_offer": 1
                        }
                    }
                ],
                "userdata": {
                    "id": 58,
                    "name": "Name",
                    "email": "xyz@gmail.com",
                    "mobileno": "98XXXXXXX"
                }
            }
        ]
    }
    }

我实现如下:

卡片的外部列表视图

 Widget _buildCardList(BuildContext context) {
return foodData.length == 0
    ? _isLoading
        ? Text("")
        : Center(
            child: Text("No Request"),
          )
    : ListView.builder(
        itemCount: foodData == null ? 0 : foodData.length,
        itemBuilder: (context, int index) {
          return Wrap(
            children: <Widget>[
              Container(
                  margin: EdgeInsets.only(bottom: 10),
                  child: Card(
                      child: Column(
                    children: <Widget>[
                      _buildCardView(context, index),
                      _cardBottomView(context, index)
                    ],
                  )))
            ],
          );
        });
      }

 Widget _buildCardView(BuildContext context, int index) {
print("Card " + index.toString());
return Wrap(
  children: <Widget>[
    Container(
      child: Container(
        margin: EdgeInsets.all(10.0),
        child: Column(
          children: <Widget>[
            _cardTopSection(context, index),
            SizedBox(
              height: 5,
            ),
            _cardFoodExplain(context),
            _cardMiddleSection(context,index),
            _cardTotalPrice(context, index),
            Container(
              height: 1,
              color: Color.fromRGBO(232, 232, 232, 1),
            ),
          ],
        ),
      ),
    ),
  ],
);
}

CardMiddleSection:

Widget _cardMiddleSection(BuildContext context, int i) {
return Container(
  margin: EdgeInsets.only(top: 10.0),
  child: ListView.builder(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      itemCount:
          foodData[i].orderdata == null ? 0 : foodData[i].orderdata.length,
      itemBuilder: (context,  i) {
        for ( i =0; i < foodData[i].orderdata.length; i++) {
          print("Card Middle" + i.toString());
          return  _cardMiddleItems(i);
        }
      }),
);
}

CardMiddleItems:

 _cardMiddleItems(int i) {
print("Card Items" + i.toString());
num total =
    foodData[i].orderdata[i].foodQty * foodData[i].orderdata[i].price;
return Container(
  margin: EdgeInsets.only(bottom: 5.0),
  child: Padding(
    padding: EdgeInsets.only(top: 3, bottom: 3),
    child: Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        Expanded(
          child: Text("${foodData[i].orderdata[i].food.name}"),
        ),
        Expanded(
          child: Center(child: Text("${foodData[i].orderdata[i].foodQty}")),
        ),
        Expanded(
          child: Text("${foodData[i].orderdata[i].price}"),
        ),
        Expanded(
          child: Text(total.toString()),
        ),
      ],
    ),
  ),
);
}

【问题讨论】:

  • itemBuilder 中,您的index 变量有两个责任,这是您的问题吗?
  • 是的...有数据列表和订单数据。在 orderdata 列表中,循环不起作用
  • @Tokenyet 请帮帮我
  • 正如我所说,您在_cardMiddleSection 中犯了一个错误,该索引有两个责任(索引= 0),但我认为您不应该为此而感到高兴,所以我发表了评论的答案。如果这解决了问题,您可以自己回答。如果没有,请编辑并发布更多信息,让观众提供帮助。
  • @Tokenyet 我尝试了所有方法但无法解决这个问题。

标签: flutter flutter-layout


【解决方案1】:

尝试摆脱诸如 index 和 i 之类的通用名称,并使用更具描述性的名称来更新您的代码,例如 foodDataIndexorderDataIndex,您应该能够看到您遇到的错误做起来更轻松。

方法 _cardMiddleItems 然后应该接受 2 个参数,而不是 1:

_cardMiddleItems(foodDataIndex, orderDataIndex) { 
  ...
}

其他一些提示

这段代码:

foodData[i].orderdata == null ? 0 : foodData[i].orderdata.length,

可以写成:

foodData[i].orderdata?.length ?? 0

与其传递索引号并使用方法,不如将其提取到单独的小部件中,并传递整个对象而不是索引号:

-itemBuilder: (context, int index) {
+itemBuilder: (context, int foodDataIndex) {
          return Wrap(
            children: <Widget>[
              Container(
                  margin: EdgeInsets.only(bottom: 10),
                  child: Card(
                      child: Column(
                    children: <Widget>[
-                      _buildCardView(context, index),
-                      _cardBottomView(context, index)
+                      CardView(foodItem=foodData[foodDataIndex]),
+                      CardBottomView(foodItem=foodData[foodDataIndex])
                    ],
                  )))
            ],
          );
        });

【讨论】:

    【解决方案2】:

    这是由于我必须处理两项任务。通过更改 _cardMiddleSection 解决了这个问题:

         Widget _cardMiddleSection(BuildContext context, int i) {
        return Container(
          margin: EdgeInsets.only(top: 10.0),
          child: ListView.builder(
              shrinkWrap: true,
              physics: const NeverScrollableScrollPhysics(),
              itemCount:
                  foodData[i].orderdata == null ? 0 : foodData[i].orderdata.length,
              itemBuilder: (context, int index) {
               return _cardMiddleItems(foodData[i].orderdata[index]);
              }),
        );
      }
    

    和 CardMiddleItems 到这个:

    _cardMiddleItems(Orderdata orderdata) {
    num total =
        orderdata.foodQty * orderdata.price;
    return Container(
      margin: EdgeInsets.only(bottom: 5.0),
      child: Padding(
        padding: EdgeInsets.only(top: 3, bottom: 3),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Expanded(
              child: Text(orderdata.food.name,textAlign: TextAlign.start,),
    
            ),
            Expanded(
              child: Center(child: Text(orderdata.foodQty.toString()))
            ),
            Expanded(
              child: Text(orderdata.price.toString(),textAlign: TextAlign.end),
            ),
            Expanded(
              child: Text(total.toString(),textAlign: TextAlign.end),
            ),
          ],
        ),
      ),
    );
    }
    

    【讨论】:

      猜你喜欢
      • 2021-01-01
      • 2020-09-25
      • 2023-04-04
      • 1970-01-01
      • 2021-02-01
      • 2020-08-30
      • 2020-06-26
      • 1970-01-01
      • 2021-03-04
      相关资源
      最近更新 更多