Wrong size for wrong orientation in Flutter

1,043

Size is determined at layout time, but your build method is called before that, at build time. However, the constraints of your widget are available at build time, and most of the time that's all you need to guess what your size is going to be. Use a LayoutBuilder to read the constraints.

screenshot1 screenshot2

import 'package:flutter/material.dart';
void main() {
  runApp(new MyApp());
}
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new MyHomePage(),
    );
  }
}
class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: new LayoutBuilder(
        builder: (BuildContext context, BoxConstraints constraints) {
          return new Text(
            '${constraints.maxWidth}x${constraints.maxHeight}',
            style: Theme.of(context).textTheme.display3,
          );
        }
      ),
    );
  }
}
Share:
1,043
user3217522
Author by

user3217522

Updated on November 30, 2022

Comments

  • user3217522
    user3217522 3 days

    I'm using the following code to get the size of a widget:

     @override
     Widget build(BuildContext context) {
        RenderBox renderBox = context.findRenderObject();
        Size size = renderBox.size;
     }
    

    However, when a rotation happens, it always returns the size of the previous orientation (for instance, if it rotates to landscape, it gives me the size of the portrait representation and vice versa). Is there a different way of getting the size of a widget on orientation change?

  • user3217522
    user3217522 about 5 years
    Yesss that's what I was missing! Thank you!