Search code examples
flutterresponsive-designflutter-layout

Flutter responsive design: Dynamically change Column to Row if the screen is larger


How to dynamically change a Column widget to a Row Widget if the screen width of the device is above a certain treshold?

The use case would be when user use the app on a tablet or landscape mode, the layout should differs in order to optimise the usage of the available width.

In CSS flexbox, it is as simple as changing the class from flex-row to flex-column but in Flutter, widgets are used.


Solution

  • Row and Column share a common parent called Flex that takes an axis direction. Simply by changing the value of direction you can change a Flex into either a row or a column.

    To get the screen width you can use MediaQuery.sizeOf(context).width.

    Your widget should look like this:

    @override
    Widget build(BuildContext context) {
      bool isScreenWide = MediaQuery.sizeOf(context).width >= kMinWidthOfLargeScreen;
    
      return Scaffold(
        body: Flex(
          direction: isScreenWide ? Axis.horizontal : Axis.vertical,
          children: <Widget>[
            ...
          ],
        )
      );
    }