flutterheight

How to resolve this error while getting height of widget?


I've tried codes from the sources listed at the bottom of the question. So, far I'm able to get the physical and logical height of the device, logical height of the onscreen keyboard, but I'm stuck on the part - getting the logical height of the widget. I tried implementing GlobalKey but did not succeed in doing so. I'm unable to get the height, and an error occurs which I did not succeed in resolving. The place of error is enclosed in multiline comment in the following code. The error says - "The property 'size' can't be unconditionally accessed because the receiver can be null. ...". I tried using ? and ! operators to resolve the null condition but nothing worked.

How can this be resolved to get the height of the widget?

import 'dart:ui';
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final GlobalKey? _key01 = GlobalKey();

  late final TextEditingController firstController;

  String result = "";
  String effective_available_screen_height = "";
  String dimensions = "";

  FlutterView view = WidgetsBinding.instance.platformDispatcher.views.first;

  late Size size;
  double width = 0;
  double height = 0;
  double height01 = 0;

  @override
  void initState() {
    super.initState();
    firstController = TextEditingController();
  }

  @override
  void dispose() {
    firstController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    Size ph_size = view.physicalSize;
    double ph_height = ph_size.height;

    size = MediaQuery.of(context).size;
    width = size.width;
    height = size.height;

    final padding = MediaQuery.of(context).viewPadding;
    height01 = height - padding.top - padding.bottom;

    effective_available_screen_height = "$height01";

    // Height of Keyboard when onscreen (ohterwise zero):
    double keyboard_height = MediaQuery.of(context).viewInsets.bottom;

    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Container(
        padding: const EdgeInsets.all(5.0),
        child: Column(
          children: [
            Container(
              child: Row(
                children: [
                  Expanded(
                    flex: 5,
                    child: Container(
                      padding: const EdgeInsets.all(5.0),
                      child: TextField(
                        key: _key01,
                        style: const TextStyle(
                          fontSize: 16,
                        ),
                        controller: firstController,
                        keyboardType: TextInputType.number,
                        onChanged: (value) {
                          setState(() {
                            result = value;
                            /*
                            // The following gave error:
                            dimensions =
                                "${_key01?.currentContext.size.height}";
                            */
                            dimensions = "${_key01?.currentContext}";
                          });
                        },
                      ),
                    ),
                  ),
                  const Expanded(
                    flex: 5,
                    child: Text("Input Value"),
                  ),
                ],
              ),
            ),
            Text("Result = $result"),
            Text("Total physical height = $ph_height"),
            Text("Total logical height = $height"),
            Text("Onscreen Keyboard height = $keyboard_height"),
            Text(
                "Working Height Available (logical) = $effective_available_screen_height"),
            Text("Dimensions: $dimensions"),
          ],
        ),
      ),
    );
  }
}

Sources of Help:


Solution

  • You just need to use this if you want to get the height when you do any action :

     dimensions ="${_key01.currentContext?.size?.height}";
    

    But if you want to get the height when the widget is rendered you can use this on initState:

       WidgetsBinding.instance.addPostFrameCallback((timeStamp) { 
           setState((){ 
              dimensions ="${_key01.currentContext?.size?.height}";
           });
    
        });