How can I have widget sizes relative to the screen size in flutter?

4,676

You can use the BuildContext context with a MediaQuery to find out the current devices screen size. For example:

    var width = MediaQuery.of(context).size.width  * 0.4; // set width to 40% of the screen width
    var height = MediaQuery.of(context).size.height  * 0.4; // set height to 40% of the screen height
Share:
4,676
Young
Author by

Young

Updated on December 08, 2022

Comments

  • Young
    Young over 1 year

    I was building a flutter app. In there I made a SliverAppBar:

    child: NestedScrollView (
      headerSliverBuilder: (BuildContext context, i) {
        return <Widget> [
          SliverAppBar (
            backgroundColor: Colors.black,
            expandedHeight: 150.0,
          )
        ];
      },
    

    I made the height to 150.0 px. But I realized that this size will change in different devices. How can I make the size take up 40% of the screen in every device?