Flutter: How to get Width and Height of a Widget

Updated: April 22, 2023 By: A Goodman Post a comment

In Flutter, you can easily get the size of a specific widget after it’s rendered. What you need to do is to give it a key, then use that key to access currentContext.size property, like this:

final _key = GlobalKey();

// This function is trggered somehow after build() called
void _getSize() {
    final size = _key.currentContext!.size;
    if (size != null) {
      final width = size.width;
      final _eight = size.height;
    }
}

Widget build(BuildContext context) {
    return Scaffold(
      child: SomeWidget(
        key: _key, 
      ),
    );
}

If you don’t clear what I mean, please see the example below for a better understanding.

Complete Example

This example demonstrates how to determine the widths and heights of a Text widget and a Card widget.

Screenshots

Portrait mode:

Landscape mode:

Note: The widths and heights of the Text and Card widgets vary by the size of the screens. That’s why you see different results in the screenshots above.

The code

The full source code with explanations:

// KindaCode.com
// main.dart
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Kindacode.com',
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  // Key and Size of the Card widget
  final _cardWidgetKey = GlobalKey();
  Size? _cardWidgetSize;

  // Key and Size of the Text widget
  final _textWidgetKey = GlobalKey();
  Size? _textWidgetSize;

  // This function is triggered when the floating button is pressed
  // You can trigger it by using other events
  void _getSize() {
    setState(() {
      _textWidgetSize = _textWidgetKey.currentContext!.size;
      _cardWidgetSize = _cardWidgetKey.currentContext!.size;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Kindacode.com'),
      ),
      body: ListView(
        children: [
          Card(
            key: _cardWidgetKey,
            margin: const EdgeInsets.all(30),
            elevation: 5,
            child: Padding(
              padding: const EdgeInsets.all(50),
              child: Center(
                child: Text(
                  'Text Widget',
                  key: _textWidgetKey,
                  style: const TextStyle(
                      fontSize: 35, backgroundColor: Colors.amber),
                ),
              ),
            ),
          ),
          Center(
            child: Text(
              _cardWidgetSize != null
                  ? 'Card Widget Size: ${_cardWidgetSize!.width.toString()} x ${_cardWidgetSize!.height.toString()}'
                  : '',
              style: const TextStyle(fontSize: 24),
            ),
          ),
          Center(
            child: Text(
              _textWidgetSize != null
                  ? 'Text Widget Size: ${_textWidgetSize!.width.toString()} x ${_textWidgetSize!.height.toString()}'
                  : '',
              style: const TextStyle(fontSize: 24),
            ),
          ),
        ],
      ),
      floatingActionButton: FloatingActionButton(
          onPressed: _getSize, child: const Icon(Icons.calculate)),
    );
  }
}

Now run the code and see your own result that shows up on the screen after you press the floating button.

Afterword

You’ve learned the technique to determine the width and height of an arbitrary widget and examined an end-to-end example of applying that knowledge in action. If you would like to explore more about Flutter, take a look at the following articles:

You can also check out our Flutter topic page or Dart topic page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles