Flutter: Get Widget size Image.file()

Issue

I want to get the size of the Widget, but it returns with Size (0,0).

@override
  Widget build(BuildContext context, WidgetRef ref) {

    useEffect((){
      WidgetsBinding.instance!.addPostFrameCallback((_){
        final size = _globalKey.currentContext?.size ?? Size(500, 500);
      });
      return;
    },const[]);

    return Scaffold(
        body: Image.file(file,key: _globalKey),
    );
  }

I can get Size by removing Scaffold…

Solution

As suggested by @pskink a layout builder and your approach might be the solution to your problem.
Nevertheless, if you want to access the this of your image you have to do it after it is render and displayed. If you use it in your state, it will probably cause glitches because it will be different between first render state and render after the render tree is fully build.
Here is a snippet showing how I access the size of an image :

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(builder: (context, constraints) {
      print(
          "scaffold -> width : ${constraints.maxWidth}, height: ${constraints.maxHeight}");
      return Scaffold(
        body: Center(child: Builder(builder: (context) {
          WidgetsBinding.instance?.addPostFrameCallback((_) {
            final RenderBox? renderBox =
                context.findRenderObject() as RenderBox?;
            final size = renderBox?.size;
            print("image after render : ${size}");
          });
          const image2 = Image(
            image: NetworkImage(
                "https://cdns.iconmonstr.com/wp-content/assets/preview/2012/240/iconmonstr-stackoverflow-2.png"),
          );
          print(
              "Image -> width : ${constraints.maxWidth}, height: ${constraints.maxHeight}");
          return image2;
        })),
      );
    });
  }
}

Then I get the output :
scaffold -> width : 1920, height: 916

Image -> width : 1920, height: 916

image after render : Size(0.0, 0.0)

Image -> width : 1920, height: 916

scaffold -> width : 1920, height: 916

Image -> width : 1920, height: 916

image after render : Size(240.0, 240.0)

image after render : Size(240.0, 240.0)

Scaffold size is constant and Image which is not bounding by any box, will render dimensions equals to its scaffold parent.
The render object is set to the display size after you display the render tree in your browser, app.

Answered By – manu

Answer Checked By – Marie Seifert (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *