Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Round image corners with BoxFit.contain in flutter

My problem is when I wrap the image with a container that has a specific size and uses BoxFit.contain property for it will not round the image. checkout the below image: image link
I think the image cant round itself because it cants expand to fill container. I know that I can use BoxFit.cover but I want to use BoxFit.contain because I have limited space and images that can be of any sizes. my code:

@override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey,
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Container(
          color: Colors.red,
          height: 300,
          width: 300,
          child: ClipRRect(
            borderRadius: BorderRadius.circular(16),
            child: Image.network(
              'https://i.ytimg.com/vi/fq4N0hgOWzU/maxresdefault.jpg',
              fit: BoxFit.contain,
            ),
          ),
        ),
      ),

    );
  }
like image 874
Payam Zahedi Avatar asked May 14 '20 16:05

Payam Zahedi


People also ask

How do you use BoxFit in Flutter?

Using BoxFit.BoxFit. none aligns the child within its parent box and discards portions outside its parent box. In the first example below, the child (100 x 50) is smaller than its parent (200 x 200). In the output, you can see that the size remains unchanged.


1 Answers

You have to wrap your ClipRRect widget with Center or any Align widget.

Most of the widgets will try to fill its parent, if the parent doesn't specify any alignment property.

In your case the ClipRRect filled its parent Container (300x300) since the container doesn't specify any alignment to its child. And Image with contain property will try to maintain image ratio and being centered in ClipRRect widget. So It made ClipRRect corners invisible or no effect.

Demo: Dartpad

Scaffold(
  backgroundColor: Colors.grey,
  appBar: AppBar(
    title: Text("My image size"),
  ),
  body: Center(
    child: Container(
      color: Colors.red,
      height: 300,
      width: 300,
      child: Center(
        child: ClipRRect(
          borderRadius: BorderRadius.circular(16),
          child: Image.network(
            'https://mfiles.alphacoders.com/847/847991.jpg',
            fit: BoxFit.contain,
          ),
        ),
      ),
    ),
  ),
)

Edit: Here I used Center widget. But you can also just simply specify alignment property in the Container widget.

like image 81
Crazy Lazy Cat Avatar answered Oct 09 '22 15:10

Crazy Lazy Cat