Home > Software engineering >  Display Image Lists from fastAPI in Flutter frontend. HTTP request failed, statusCode: 500
Display Image Lists from fastAPI in Flutter frontend. HTTP request failed, statusCode: 500

Time:06-21

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.

CodePudding user response:

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"
],
  • Related