shankyyyyyyy
shankyyyyyyy

Reputation: 97

Flutter : infinite width

I'm doing a flutter course, and here is my relevent code :

Container(
                  color: kBottomContainerColour,
                  margin: EdgeInsets.only(top: 10.0),
                  width: double.infinity,
                  height: kBottomContainerHeight,
                ),

And I keep getting this :

These invalid constraints were provided to _RenderColoredBox's layout() function by the following function, which probably computed the invalid constraints in question:
  RenderConstrainedBox.performLayout (package:flutter/src/rendering/proxy_box.dart:268:14)
The offending constraints were: BoxConstraints(w=Infinity, h=80.0)
The relevant error-causing widget was: 
  Container file:///F:/Works/Projects/flutter/Flutter-Course-Resources/bmi-calculator-flutter1/lib/input_page.dart:241:24

Though it is working fine in the course Please help

Upvotes: 3

Views: 13854

Answers (3)

Chema
Chema

Reputation: 745

As of 2024, you can use MediaQuery.sizeOf(context).width to only redraw on resize:

Querying using MediaQuery.of will cause your widget to rebuild automatically whenever any field of the MediaQueryData changes (e.g., if the user rotates their device). Therefore, unless you are concerned with the entire MediaQueryData object changing, prefer using the specific methods (for example: MediaQuery.sizeOf and MediaQuery.paddingOf).

https://api.flutter.dev/flutter/widgets/MediaQuery-class.html

Upvotes: 0

Ronak Patel
Ronak Patel

Reputation: 629

Instead of width: double.infinity,

Use,

width: MediaQuery.of(context).size.width

Upvotes: 6

Dan Gerchcovich
Dan Gerchcovich

Reputation: 525

Don't use double.infinity. Use the MediaQuery to get the size from the current widget context, and get the width from that. In this case do this:

Container(color: kBottomContainerColour,
                  margin: EdgeInsets.only(top: 10.0),
                  width: MediaQuery.of(context).size.width
                  height: kBottomContainerHeight,
                ),

Please note that everytime you use MediaQuery the widget will reload its state. So make sure break your widgets down, and follow google's performance guidelines:

https://flutter.dev/docs/perf/rendering/best-practices

Upvotes: 2

Related Questions