flutter

Assign width in percentage to flutter container

We will assign the width in percentage to the Flutter container and make it fluid. This ensures that, no matter what device you’re on, Flutter doesn’t take up more than its fair share of space and the app is easy to use and fast at all times.

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    double width50 = MediaQuery.of(context).size.width * 0.50;
    
    return Container(
        width: width50,
        child: const Text('Some Text'),
      );
  }
}

The above code snippet will assign a 50 percent width to the flutter container widget. We are using MediaQuery.of(context) in Flutter and getting the size of the screen using the code.

MediaQuery.of(context).size.width

We will get the full width of the device screen using the above code. Then we are multiplying it by 0.50 to get the half-width of the screen and assign it to the width property of the Flutter Container widget.

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    double width30 = MediaQuery.of(context).size.width * 0.30;
    
    return Scaffold(
        appBar: AppBar(
            title: const Text("APP DEMO"),
        ),
        body: Container(
            width: width30,
            color: const Color(0xffCCCCCC),
            child: Text('Hello World'),
        ),
    );
  }
}
Here we are assigning a 30 percent width to the Flutter container widget. We are using MediaQuery to get the width of the screen.
class FullWidthPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    double width50 = MediaQuery.of(context).size.width;
    
    return Scaffold(
        appBar: AppBar(
            title: const Text("APP DEMO"),
        ),
        body: Container(
            width: width50,
            color: const Color(0xffCCCCCC),
            child: const Text('Hello World'),
        ),
    );
  }
}
The above code can be used to assign a full width to the Flutter container.
Container(
    width: double.infinity,
    color: const Color(0xffCCCCCC),
    child: const Text('Hello World'),
),
We can also assign a full width to the Flutter container using double.infinity.
Was this helpful?