flutterflutter-layout

proper way to get widget height in SafeArea


I'm trying to get the height of widget but it prints the same values

I/flutter (19253): full height: 976.0
I/flutter (19253): safe height: 976.0

I guessed the second value should be smaller because the Container placed below the status bar. What I'm doing wrong? I need height because in this container will be Wrap widget (actually ReorderableWrap https://pub.dartlang.org/packages/reorderables#-readme-tab-) with 36 cards, 3 rows by 12 cards and cards height must be 1/3 of its container.

I didn't find good Reorderable Grid. But anyway my question why a Container in a safe area has the same height as Container that fills the entire screen?

import 'package:flutter/material.dart';

void main() {
  runApp(_MyApp());
}

class _MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(body: _Body()),
    );
  }
}

class _Body extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    print('full height: ${MediaQuery.of(context).size.height}');
    return Container(
      constraints: BoxConstraints.expand(),
      decoration: BoxDecoration(color: Colors.red),
      child: SafeArea(
        child: _SafeHeightWidget(),
      ),
    );
  }
}

class _SafeHeightWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    print('safe height: ${MediaQuery.of(context).size.height}');
    return Container(
      color: Colors.lightBlue,
    );
  }
}

Solution

  • You can always use LayoutBuilder for such cases.

    child: SafeArea(
            child: new LayoutBuilder(
                builder: (BuildContext context, BoxConstraints constraints) {
                  // constraints variable has the size info
                  return Container();
                }
            ),
          ),
    

    for more info: https://www.youtube.com/watch?v=IYDVcriKjsw