Skip to content

MediaQuery.of(context).size.height returns 0 on startup in release mode #25827

Closed

Description

@yunyu

I have a widget which is a member of a stack that's in the body of Scaffold:

MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: Scaffold(
            body: Stack(
                children: [MyWidget()],
                alignment: Alignment.bottomCenter)));
  }

When I log MediaQuery.of(context).size.height in MyWidget's build() function, I get the following output in release mode:

12-27 18:43:39.650 12694 12740 I flutter : Context height: 0.0
12-27 18:43:39.854 12694 12740 I flutter : Context height: 731.4285714285714

The behavior is as expected in debug mode (height is never 0.0). I am doing some calculations with this
value that would result in some widgets having infinite height, which causes the application to freeze on startup.

Activity

  1. zoechi commented on Dec 28, 2018

    @zoechi
    Contributor

    That's because Flutter starts quicker in release mode and the native platform reports the actual resolution with a delay.
    Just handle the case that the size is 0/0 at first.

  2. added
    frameworkflutter/packages/flutter repository. See also f: labels.
    d: api docsIssues with https://api.flutter.dev/
    on Dec 28, 2018
  3. added this to the milestone on Dec 28, 2018
  4. reopened this on Dec 28, 2018
  5. HansMuller commented on Jan 2, 2019

    @HansMuller
    Contributor

    Related problem with TabBar: #23339 (comment)

  6. gordon-rawe commented on Jan 3, 2019

    @gordon-rawe

    did you solved this problem?

  7. zoechi commented on Jan 3, 2019

    @zoechi
    Contributor

    @gordon-rawe there shouldn't be much to solve.
    Just make your code resilient against 0 values so that it doesn't cause an error.
    Shortly afterwards your app will be rebuilt again with the proper value.

  8. dsrenesanse commented on Feb 24, 2019

    @dsrenesanse

    looks like a crutch

  9. leen-nobbas commented on Mar 21, 2019

    @leen-nobbas

    That is not a good thing!

  10. lianhuilui commented on Mar 24, 2019

    @lianhuilui

    Ran into the same problem. I was debugging for hours until I found out that size was empty. There was no hot-reload in release mode so it made debugging much more difficult.

  11. HipSze commented on Mar 25, 2019

    @HipSze

    same problem, I just release my app on store.

  12. joseph-montanez commented on Mar 30, 2019

    @joseph-montanez

    I've created a video and quick gist on this issue with a solution.

    Video https://www.youtube.com/watch?v=zp26UXInb4s&feature=youtu.be
    Gist https://gist.github.com/joseph-montanez/c7316b89c9a458a34c6381840cc6d1de

    Basically, you need to switch out to use FutureBuilder and use a stream with a future to watch and capture the value once it's not zero.

    Here is an example function to capture to streams value into a future:

    Future<double> whenNotZero(Stream<double> source) async {
        await for (double value in source) {
            print("Width:" + value.toString());
            if (value > 0) {
                print("Width > 0: " + value.toString());
                return value;
            }
        }
        // stream exited without a true value, maybe return an exception.
    }

    Then in your widgets you specify the furture builder. In this example I an checking every 50 milliseconds to MediaQuery.of(context).size.width to see if its greater than 0.

    FutureBuilder(
        future: whenNotZero(
            Stream<double>.periodic(Duration(milliseconds: 50),
                (x) => MediaQuery.of(context).size.width),
        ),
        builder: (BuildContext context, snapshot) {
            if (snapshot.hasData) {
                if (snapshot.data > 0) {
                    return Container( 
                        child: //... Your widgets here!
                    );
                }
            } else {
                return Container();
            }
        }
    ),

    @zoechi hopefully this will be a better answers, as there are multiple reports of this issue.

  13. jefferybai commented on Apr 26, 2019

    @jefferybai

    same problem, I just release my app on store.

  14. jlab13 commented on Sep 19, 2019

    @jlab13

    same problem, I just release my app on store.

  15. topilski commented on Nov 28, 2019

    @topilski

    any updates? it is big problem because in build we have different layouts, which we select according sizes, you should guaranties that in build we have valid context and in didChangeDependencies as well.

  16. JSBmanD commented on Dec 26, 2019

    @JSBmanD

    Anyone solved the issue?

  17. kf6gpe commented on Jan 7, 2020

    @kf6gpe
    Contributor

    This is by design for performance reasons, as @zoechi mentions. I'm going to close this issue with the ways to work with this currently listed here.

  18. szbk commented on Jan 13, 2020

    @szbk

    I had a similar problem. I solved it like this;

    img

  19. sciobotaru commented on Sep 3, 2020

    @sciobotaru

    Had the exact same issue. I have changed the code as follow, then everything worked fine in release mode:

    @OverRide
    Widget build(BuildContext context) {
    InitialData.phoneSize = MediaQuery
    .of(context)
    .size;

    if (InitialData.phoneSize.width == 0 || InitialData.phoneSize.height == 0) {
      return Container(
        child: Center(
          child: Text("Loading..."),
        ),
      );
    } else {
      return SafeArea(
        child: Scaffold(
          body: Column(
            children: [
              MenuArea(),
              PlayArea(),
            ],
          ),
        ),
      );
    }
    

    }

  20. sciobotaru commented on Sep 3, 2020

    @sciobotaru

    That's because Flutter starts quicker in release mode and the native platform reports the actual resolution with a delay.
    Just handle the case that the size is 0/0 at first.

    Thanks, man! Your comment really helped me.

  21. teneon commented on Feb 13, 2021

    @teneon

    I've encountered this problem yesterday. It never happened on emulator. But then i tested my app on real device and MediaQuery.of(context).size.width returned 0. The UI of course didn't work properly because of this. When i "hot restarted" the app, it returned proper width. I also tried to stop the app and restarted it.., but it didn't happen again. It happens only every now and then. So it's kind of a hidden "bug". I think, this should be resolved somehow or at least some official docs how to handle this issue? I have now implemented the solution provided by @joseph-montanez ,but i am not sure if this is the best possible approach? Isn't there something more "clean"? Is anyone even aware of this problem? I think it should be marked as a bug.

  22. tjx666 commented on Mar 30, 2021

    @tjx666

    @teneon
    This seems to be more simple refer to https://github.com/OpenFlutter/flutter_screenutil/blob/20ac1de0f2f2b95d43922d1567fa2aa1629c8cee/lib/screenutil_init.dart#L22.

    Widget build(BuildContext context) {
        return LayoutBuilder(
          builder: (context, constraints) {
            if (constraints.maxWidth != 0) {
              return MaterialApp(
                home: HomePage()
            }
            return Container();
          },
        );
      }
  23. github-actions commented on Aug 3, 2021

    @github-actions

    This thread has been automatically locked since there has not been any recent activity after it was closed. If you are still experiencing a similar issue, please open a new bug, including the output of flutter doctor -v and a minimal reproduction of the issue.

  24. locked as resolved and limited conversation to collaborators on Aug 3, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    d: api docsIssues with https://api.flutter.dev/frameworkflutter/packages/flutter repository. See also f: labels.

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions