I am trying to work on a project that should be run on web, tablet and mobile platforms. I think there are 2 approaches to do this:
1- Create 3 different widgets for each page of the app. For example:
import 'package:flutter/material.dart';
class ResponsiveLayout extends StatelessWidget {
final Widget mobileBody;
final Widget tabletBody;
final Widget desktopBody;
ResponsiveLayout({
required this.mobileBody,
required this.tabletBody,
required this.desktopBody,
});
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) {
if (constraints.maxWidth < 500) {
return mobileBody;
} else if (constraints.maxWidth < 1100) {
return tabletBody;
} else {
return desktopBody;
}
},
);
}
}
2- Create only one widget for each screen but check the screen size like mediaquery.of(context).size.width
whenever I want to show something differently on web than mobile or table.
I don't know there is also a third approach or which approach is better for big application/projects?
CodePudding user response:
You might want to check out this package:
https://pub.dev/packages/sizer
It is very helpful when working for multiple screen sizes. From their README:
- h - Returns a calculated height based on the device
- .w - Returns a calculated width based on the device
- .sp - Returns a calculated sp based on the device
- SizerUtil.orientation - for screen orientation portrait or landscape
- SizerUtil.deviceType - for device type mobile or tablet
CodePudding user response:
Basically, these are 2 ways to handle it.
The tradeoffs here are complexity, flexibility, speed of development and consistency:
if you create 3 separate widgets, you might need to spend more time to preserve consistency (copy code changes between widgets) sometimes, but each widget would be more or less simple to understand.
if you use MediaQuery.of(context) and all the changes automatically propagate to all the versions (which might be a good or a bad thing) and it's way more flexible (i.e. you can show/hide/change some parts of the widget at width < 500 and others at width < 1200), but the code might slowly turn into an unreadable mess.
Here's more info in the official doc