1
votes

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?

1

1 Answers

4
votes

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,
          );
        }
      ),
    );
  }
}