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.
There are two basic approaches to creating Flutter apps with responsive design: Use the LayoutBuilder class. From its builder property, you get a BoxConstraints object. Examine the constraint's properties to decide what to display.
To create a row or column in Flutter, you add a list of children widgets to a Row or Column widget. In turn, each child can itself be a row or column, and so on. The following example shows how it is possible to nest rows or columns inside of rows or columns. The left column's widget tree nests rows and columns.
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.of(context).size.width
.
Your widget should look like this:
@override
Widget build(BuildContext context) {
bool isScreenWide = MediaQuery.of(context).size.width >= kMinWidthOfLargeScreen;
return Scaffold(
body: Flex(
direction: isScreenWide ? Axis.horizontal : Axis.vertical,
children: <Widget>[
...
],
)
);
}
To change based on device orientation, you can do:
Orientation orientation = MediaQuery.of(context).orientation;
return orientation == Orientation.portrait
? Column(children: <Widget>[])
: Row(children: <Widget>[]);
I wrote a helper to do this (Column to Row).
import 'package:flutter/material.dart';
class OrientationSwitcher extends StatelessWidget {
final List<Widget> children;
const OrientationSwitcher({Key key, this.children}) : super(key: key);
@override
Widget build(BuildContext context) {
Orientation orientation = MediaQuery.of(context).orientation;
return orientation == Orientation.portrait
? Column(children: children)
: Row(children: children);
}
}
And to use it...
Widget build(BuildContext context) {
return OrientationSwitcher(
children: <Widget>[
// place children here like its a column or row.
]
)
}
You also can do this with Flex() or any other widget.
Also, there are more options available besides orientation, make sure to look at the MediaQuery.of(context) implementation on the Flutter docs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With