How can you "center crop" a Widget in Flutter?

Finally solved it. There were a few missing pieces:

  1. I needed an OverflowBox with no restrictions so that my child could grow as large as needed.
  2. I needed the child of FittedBox to actually enforce a size to stop the layout system from crashing.
  3. Now that my widget will paint outside of its bounds, we also want to put a ClipRect in there to stop this from happening.
final Size size = controller.value.size;
return new ClipRect(
  child: new OverflowBox(
    maxWidth: double.infinity,
    maxHeight: double.infinity,
    alignment: Alignment.center,
    child: new FittedBox(
      fit: BoxFit.cover,
      alignment: Alignment.center,
      child: new Container(
        width: size.width,
        height: size.height,
        child: new VideoPlayer(controller)
      )
    )
  )
);

Starting with the above solution I came up with this:

final Size size = _controller.value.size;
return Container(
  color: Colors.lightBlue,
  width: MediaQuery.of(context).size.width,
  height: MediaQuery.of(context).size.width,
  child: FittedBox(
           alignment: Alignment.center,
       fit: BoxFit.fitWidth,
       child: Container(
         width: size.width,
         height: size.height,
         child: VideoPlayer(_controller))),
      ),
)

The inner Container provides the size for the Texture inside the VideoPlayer.


I know the question is old, but imma post it here so if others find it they find another solution. So basically, if you always want a picture to cover an area, but wanna always show the middle of the picture (center crop i guess) create a sizedbox around the image. You may say it is not responsive or has to be hardcoded. Just calculate it from something. I did like that:

class HomePage extends StatelessWidget{
  @override
  Widget build(BuildContext context)=>SizedBox(child: Image.asset("home.jpg",fit: BoxFit.cover,),width: isWide ? MediaQuery.of(context).size.width-350 : MediaQuery.of(context).size.width,height: MediaQuery.of(context).size.height,);
}

Here, i even check the "resolution of the device". isWide boolean is true, if MediaQuery.orientation == landscape. If so, i have a 350px menu on the left side, so i can calculate the remaining space for the sizedbox. Hope this helps!

Tags:

Flutter