显示Flutter Frontend的Fastapi的图像列表。 HTTP请求失败,状态代码:500

发布于 2025-02-09 00:09:30 字数 6443 浏览 0 评论 0原文

我正在尝试从扑波图中的图像列表中选择一个索引。在将图像列表传递到 image.network()时,我会遇到一个错误:

The following NetworkImageLoadException was thrown resolving an image codec:
HTTP request failed, statusCode: 500, http://10.0.2.2:8000/static/product_images/b0bf3474f9c5a6b6cfcf.jpg,http://10.0.2.2:8000/static/product_images/e307dccf6bbc2700e683.jpg,http://10.0.2.2:8000/static/product_images/6e91cff1ce07d72fc127.jpg

请如何将图像分开,以便仅选择我选择的索引? 以下是产品模型:

import 'dart:convert';

List<ProductModel> productsFromJson(String str) => List<ProductModel>.from(
    json.decode(str).map((x) => ProductModel.fromJson(x)));

String productsToJson(List<ProductModel> data) =>
    json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class ProductModel {
  ProductModel({
    required this.name,
    required this.price,
    required this.isActive,
    required this.imgsUrl,
    required this.id,
    required this.description,
    required this.ownerId,
  });

  String name;
  double price;
  bool isActive;
  List<String> imgsUrl;
  int id;
  String description;
  int ownerId;

  factory ProductModel.fromJson(Map<String, dynamic> json) => ProductModel(
        name: json["name"],
        price: json["price"].toDouble(),
        isActive: json["is_active"],
        imgsUrl: List<String>.from(json["imgs_url"].map((x) => x)),
        id: json["id"],
        description: json["description"],
        ownerId: json["owner_id"],
      );

  Map<String, dynamic> toJson() => {
        "name": name,
        "price": price,
        "is_active": isActive,
        "imgs_url": List<dynamic>.from(imgsUrl.map((x) => x)),
        "id": id,
        "description": description,
        "owner_id": ownerId,
      };
}

我使用带有DIO的FutureBuilder来获取API的数据:

FutureBuilder<List<ProductModel>>(
          future: productModel,
          builder: (context, snapshot) {
            if (snapshot.hasError) {
              return Text('${snapshot.error}');
            } else if (snapshot.hasData) {
              debugPrint('${snapshot.data}');
              return SizedBox(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Center(
                      child: Container(
                        decoration: const BoxDecoration(
                            color: styles.AppColors.facebookBlue),
                        child: Text('$finalName products online'),
                      ),
                    ),
                    Expanded(
                      child: StaggeredGridView.countBuilder(
                        crossAxisCount: 2,
                        itemCount: snapshot.data!.length,
                        itemBuilder: (context, index) {
                          return Card(
                            child: Padding(
                              padding: const EdgeInsets.all(8.0),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Stack(children: [
                                    Container(
                                        height: 180,
                                        width: double.infinity,
                                        clipBehavior: Clip.antiAlias,
                                        decoration: BoxDecoration(
                                            borderRadius:
                                                BorderRadius.circular(4)),
                                        child:
                                            Image.network(snapshot
                                                .data![index].imgsUrl[0])
                                  ]),
                                  const SizedBox(
                                    height: 8,
                                  ),
                                  Text(snapshot.data![index].name),
                                  Text(
                                    "\$${snapshot.data![index].price.toString()}",
                                  )
                                ],
                              ),
                            ),
                          );
                        },
                        staggeredTileBuilder: (int index) =>
                            const StaggeredTile.fit(1),
                        mainAxisSpacing: 10,
                        crossAxisSpacing: 10,
                      ),
                    ),
                  ],
                ),
              );
            } else {
              return const Center(child: CircularProgressIndicator());
            }
          }),

对于Dioclient的API调用:

Future<List<ProductModel>> fetchVProduct() async {
    await SecureStorage.readSecureData("vt")
        .then((value) => finalToken = value);
    try {
      final response = await Dio().get(
        '$productsEndpoint/me/items/',
        options: Options(
            headers: {
              'Content-Type':
                  'application/x-www-form-urlencoded;charset=UTF-8;application/json;multipart/form-data',
              'Accept': 'application/json',
              "Authorization": "Bearer $finalToken",
            },
            followRedirects: false,
            validateStatus: (status) {
              return status! < 500;
            }),
      );
      debugPrint(response.toString());
      return (response.data as List)
          .map((x) => ProductModel.fromJson(x))
          .toList();
    } on DioError catch (e) {
      debugPrint("Status code: ${e.response?.statusCode.toString()}");
      throw Exception("Failed to load currently Logged in Vendor Products");
    }
  }

对于我的Apicall的示例JSON:

{
    "name": "sa",
    "price": 44,
    "is_active": true,
    "imgs_url": [
      "http://10.0.2.2:8000/static/product_images/f3e6421737643e583a1d.jpg, http://10.0.2.2:8000/static/product_images/b53bf8aeb27d27a739cc.jpg, http://10.0.2.2:8000/static/product_images/75a80e7c04ebaed3e425.jpg"
    ],
    "id": 43,
    "description": "hfg",
    "owner_id": 1
  }

请下一步该怎么办?谢谢。

I am trying to select an index from a list of images in flutter. While passing the image list to the Image.network() i get an error:

The following NetworkImageLoadException was thrown resolving an image codec:
HTTP request failed, statusCode: 500, http://10.0.2.2:8000/static/product_images/b0bf3474f9c5a6b6cfcf.jpg,http://10.0.2.2:8000/static/product_images/e307dccf6bbc2700e683.jpg,http://10.0.2.2:8000/static/product_images/6e91cff1ce07d72fc127.jpg

Please how do i seperate the images so that only the index i pick is selected?
Below is the Product Model:

import 'dart:convert';

List<ProductModel> productsFromJson(String str) => List<ProductModel>.from(
    json.decode(str).map((x) => ProductModel.fromJson(x)));

String productsToJson(List<ProductModel> data) =>
    json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class ProductModel {
  ProductModel({
    required this.name,
    required this.price,
    required this.isActive,
    required this.imgsUrl,
    required this.id,
    required this.description,
    required this.ownerId,
  });

  String name;
  double price;
  bool isActive;
  List<String> imgsUrl;
  int id;
  String description;
  int ownerId;

  factory ProductModel.fromJson(Map<String, dynamic> json) => ProductModel(
        name: json["name"],
        price: json["price"].toDouble(),
        isActive: json["is_active"],
        imgsUrl: List<String>.from(json["imgs_url"].map((x) => x)),
        id: json["id"],
        description: json["description"],
        ownerId: json["owner_id"],
      );

  Map<String, dynamic> toJson() => {
        "name": name,
        "price": price,
        "is_active": isActive,
        "imgs_url": List<dynamic>.from(imgsUrl.map((x) => x)),
        "id": id,
        "description": description,
        "owner_id": ownerId,
      };
}

I am using a futurebuilder with dio to fetch the data from the API:

FutureBuilder<List<ProductModel>>(
          future: productModel,
          builder: (context, snapshot) {
            if (snapshot.hasError) {
              return Text('${snapshot.error}');
            } else if (snapshot.hasData) {
              debugPrint('${snapshot.data}');
              return SizedBox(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Center(
                      child: Container(
                        decoration: const BoxDecoration(
                            color: styles.AppColors.facebookBlue),
                        child: Text('$finalName products online'),
                      ),
                    ),
                    Expanded(
                      child: StaggeredGridView.countBuilder(
                        crossAxisCount: 2,
                        itemCount: snapshot.data!.length,
                        itemBuilder: (context, index) {
                          return Card(
                            child: Padding(
                              padding: const EdgeInsets.all(8.0),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Stack(children: [
                                    Container(
                                        height: 180,
                                        width: double.infinity,
                                        clipBehavior: Clip.antiAlias,
                                        decoration: BoxDecoration(
                                            borderRadius:
                                                BorderRadius.circular(4)),
                                        child:
                                            Image.network(snapshot
                                                .data![index].imgsUrl[0])
                                  ]),
                                  const SizedBox(
                                    height: 8,
                                  ),
                                  Text(snapshot.data![index].name),
                                  Text(
                                    "\${snapshot.data![index].price.toString()}",
                                  )
                                ],
                              ),
                            ),
                          );
                        },
                        staggeredTileBuilder: (int index) =>
                            const StaggeredTile.fit(1),
                        mainAxisSpacing: 10,
                        crossAxisSpacing: 10,
                      ),
                    ),
                  ],
                ),
              );
            } else {
              return const Center(child: CircularProgressIndicator());
            }
          }),

For the API call with DioClient:

Future<List<ProductModel>> fetchVProduct() async {
    await SecureStorage.readSecureData("vt")
        .then((value) => finalToken = value);
    try {
      final response = await Dio().get(
        '$productsEndpoint/me/items/',
        options: Options(
            headers: {
              'Content-Type':
                  'application/x-www-form-urlencoded;charset=UTF-8;application/json;multipart/form-data',
              'Accept': 'application/json',
              "Authorization": "Bearer $finalToken",
            },
            followRedirects: false,
            validateStatus: (status) {
              return status! < 500;
            }),
      );
      debugPrint(response.toString());
      return (response.data as List)
          .map((x) => ProductModel.fromJson(x))
          .toList();
    } on DioError catch (e) {
      debugPrint("Status code: ${e.response?.statusCode.toString()}");
      throw Exception("Failed to load currently Logged in Vendor Products");
    }
  }

For the sample json from my apicall:

{
    "name": "sa",
    "price": 44,
    "is_active": true,
    "imgs_url": [
      "http://10.0.2.2:8000/static/product_images/f3e6421737643e583a1d.jpg, http://10.0.2.2:8000/static/product_images/b53bf8aeb27d27a739cc.jpg, http://10.0.2.2:8000/static/product_images/75a80e7c04ebaed3e425.jpg"
    ],
    "id": 43,
    "description": "hfg",
    "owner_id": 1
  }

Please what do i do next? Thank you.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

徒留西风 2025-02-16 00:09:31

在数据IMGS_URL中是一个包含三个URL的单字符串。

"imgs_url": [
  "http://10.0.2.2:8000/static/product_images/f3e6421737643e583a1d.jpg, http://10.0.2.2:8000/static/product_images/b53bf8aeb27d27a739cc.jpg, http://10.0.2.2:8000/static/product_images/75a80e7c04ebaed3e425.jpg"
],

将其更改为

"imgs_url": [
  "http://10.0.2.2:8000/static/product_images/f3e6421737643e583a1d.jpg", 
  "http://10.0.2.2:8000/static/product_images/b53bf8aeb27d27a739cc.jpg", 
  "http://10.0.2.2:8000/static/product_images/75a80e7c04ebaed3e425.jpg"
],

In data imgs_url is a single string containing three urls.

"imgs_url": [
  "http://10.0.2.2:8000/static/product_images/f3e6421737643e583a1d.jpg, http://10.0.2.2:8000/static/product_images/b53bf8aeb27d27a739cc.jpg, http://10.0.2.2:8000/static/product_images/75a80e7c04ebaed3e425.jpg"
],

Change it to

"imgs_url": [
  "http://10.0.2.2:8000/static/product_images/f3e6421737643e583a1d.jpg", 
  "http://10.0.2.2:8000/static/product_images/b53bf8aeb27d27a739cc.jpg", 
  "http://10.0.2.2:8000/static/product_images/75a80e7c04ebaed3e425.jpg"
],
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文