Flutter - BoxConstraints forces an infinite width/height Error

In this article, I am going to show you how to solve the "BoxConstraints forces an infinite width/height" error in Flutter. This error occurs when the parent widget has an infinite container and the child widget has infinite width or height.

Maybe you've seen the below error during flutter development.

══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞══════════════════
The following assertion was thrown during performLayout():
BoxConstraints forces an infinite width.
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:277:14)
The offending constraints were:

BoxConstraints forces an infinite width/height Error may come a different way let's see one by one.

Error Infinite Height in Column() :

Column(
  children:[
    Container(
       child:Text("Errorgram"),
       height: double.infinity,
    )
  ]
) 

 

Solution:

When we put child widget to Column with infinite height, you may get "BoxConstraints forces an infinite height." Error. To solve this error, you should bound the height of the child widget with Expanded() widget like below example:

Column(
  children:[
    Expanded(
      child:Container(
         child:Text("Errorgram"),
         height: double.infinity,
      )
    )
  ]
)

 

Error Infinite Width in Row() : 

Row(
  children:[
      Container(
        child:Text("Errorgram"),
        width: double.infinity,
      )
  ]
)

 

Solution:

When we put children in Row() widget with infinite width, you may get "BoxConstraints forces an infinite width." error. To solve this error, wrap your child widgets with Expanded() widget instead of giving its width infinite.

Row(
  children:[
      Expanded(
        child:Container(
            child:Text("Errorgram"),
            width: double.infinity,
        )
      )
  ]
)

 

Error infinite Widget Positioned :

When Positioned() widget has a child with infinite width on the condition below, you may get the error "BoxConstraints forces an infinite width".

Positioned(
    bottom: 10,
    child: Container( 
	  child:Text("Errorgram"),
      width: double.infinity,//Error will occur BoxConstraints forces an infinite width
    ),
) 
Positioned(
    top: 10,
    child: Container( 
	  child:Text("Errorgram"),
      height: double.infinity, //Error will occur BoxConstraints forces an infinite height
    ),
) 

 

Solution:

We can set the height and width to the child widget like below.

Positioned(
    bottom:50,
    child: Container( 
	child:Text("Errorgram"),
    color: Colors.yellow,
      height: 200,
      width: 350,
    ),
)

In this way, we can solve "BoxConstraints forces an infinite width/height" error in the Flutter. I hope it will help you.

Tags: