Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
yunyu opened this issue Dec 28, 2018 · 20 comments
Closed

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

yunyu opened this issue Dec 28, 2018 · 20 comments
Labels
d: api docs Issues with https://api.flutter.dev/ framework flutter/packages/flutter repository. See also f: labels.

Comments

@yunyu
Copy link

yunyu commented Dec 28, 2018

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.

@zoechi
Copy link
Contributor

zoechi commented Dec 28, 2018

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.

@zoechi zoechi closed this as completed Dec 28, 2018
@zoechi zoechi added framework flutter/packages/flutter repository. See also f: labels. d: api docs Issues with https://api.flutter.dev/ labels Dec 28, 2018
@zoechi zoechi added this to the Goals milestone Dec 28, 2018
@zoechi zoechi reopened this Dec 28, 2018
@HansMuller
Copy link
Contributor

Related problem with TabBar: #23339 (comment)

@gordon-rawe
Copy link

did you solved this problem?

@zoechi
Copy link
Contributor

zoechi commented Jan 3, 2019

@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.

@machinescream
Copy link

looks like a crutch

@leen-nobbas
Copy link

That is not a good thing!

@lianhuilui
Copy link

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.

@HipSze
Copy link

HipSze commented Mar 25, 2019

same problem, I just release my app on store.

@joseph-montanez
Copy link

joseph-montanez commented Mar 30, 2019

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.

@jefferybai
Copy link

same problem, I just release my app on store.

CZX123 added a commit to CZX123/Bolt that referenced this issue Jun 9, 2019
Fk this stupid bug.
flutter/flutter#25827
(More about the bug: This was a bug where the CustomBottomSheet did not appear in release mode. The reason was due to the issue above. I took fking forever to solve this shit)
@jlab13
Copy link

jlab13 commented Sep 19, 2019

same problem, I just release my app on store.

@topilski
Copy link

topilski commented Nov 28, 2019

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.

@JSBmanD
Copy link

JSBmanD commented Dec 26, 2019

Anyone solved the issue?

@kf6gpe
Copy link
Contributor

kf6gpe commented Jan 7, 2020

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.

@kf6gpe kf6gpe closed this as completed Jan 7, 2020
@szbk
Copy link

szbk commented Jan 13, 2020

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

img

@sciobotaru
Copy link

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

}

@sciobotaru
Copy link

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.

@teneon
Copy link

teneon commented Feb 13, 2021

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.

@tjx666
Copy link

tjx666 commented Mar 30, 2021

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

@github-actions
Copy link

github-actions bot commented Aug 3, 2021

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.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Aug 3, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
d: api docs Issues with https://api.flutter.dev/ framework flutter/packages/flutter repository. See also f: labels.
Projects
None yet
Development

No branches or pull requests