Abubakar Siddique
Abubakar Siddique

Reputation: 1

How to display images in flutter with different dimensions inside a fixed-size container while maintaining aspect ratio and ensuring a clean UI?

Column(
    crossAxisAlignment: CrossAxisAlignment.start,
    children: [
         ClipRRect(
            borderRadius: const BorderRadius.only(
                  topLeft: Radius.circular(10),
                  topRight: Radius.circular(10)),
                  child: AppStyles.displayImage(
                          recentCourse.coverPicture,
                          width: MediaQuery.of(context).size.width,
                           height: 200,
                  ),  

Here's the code in my constant class:

    static Widget displayImage(String? imageUrl,
      {required double? width, required double? height}) {
      if (imageUrl != null && imageUrl.startsWith('http')) {
      return CachedNetworkImage(
        imageUrl: imageUrl,
        width: width,
        height: height,
        fit: BoxFit.contain,
        placeholder: (context, url) => Shimmer.fromColors(
          baseColor: Colors.grey.shade300,
          highlightColor: Colors.grey.shade100,
          child: Container(
            width: width,
            height: height,
            color: Colors.grey.shade300,
          ),
        ),
        errorWidget: (context, url, error) => Image.asset(
          'assets/images/placeholder.png',
          width: width,
          height: height,
          fit: BoxFit.cover,
        ),
      );
    } else {
      // Display fallback asset image if the URL is null or invalid
      return const Text(
        "No Image\nto display/nURL is null",
        style: TextStyle(
            fontSize: 12, color: Colors.red, fontWeight: FontWeight.bold),
      );
    }
  }

This is the code which I am using and I have tried all the fit: property in the CachedNetworkImage none of them worked for me.

In the display image, if I increase height for the specific image, it may look good, but other images it won't.

In short what I require is: I will be getting images with different size, I need to display all of those images with proper same height and width to look good in my app.

Any suggestions will be appreciated. Thank you for your time

Upvotes: 0

Views: 47

Answers (0)

Related Questions