I want to make a responsive widget. I want it to change to another style of screen when using a different device.
I’ve read multiple questions like this, but still can’t find an answer. The answer is pretty much checking if the device is mobile, tablet or desktop by screen width. If I do this, when I rotate the mobile device, it shows the tablet style screen even though I’m using a mobile device.
However, I see an answer that uses the package, not the way. However, I get the following error when using the package:
════════ Exception caught by widgets library ═══════════════════════════════════
LateInitializationError: Field 'deviceType' has not been initialized.
The relevant error-causing widget was
LayoutBuilder
lib/…/responsive.dart:18
════════════════════════════════════════════════════════════════════════════════
My code:
import 'package:flutter/material.dart';
import 'package:sizer/sizer.dart';
class Responsive extends StatelessWidget {
const Responsive({required this.mobile, required this.tablet, required this.desktop, super.key});
final Widget mobile;
final Widget tablet;
final Widget desktop;
static bool isMobile(BuildContext context) => MediaQuery.of(context).size.width < 600.0 && SizerUtil.deviceType == DeviceType.mobile;
static bool isTablet(BuildContext context) => MediaQuery.of(context).size.width < 1100.0 && MediaQuery.of(context).size.width >= 600.0 && SizerUtil.deviceType == DeviceType.tablet;
static bool isDesktop(BuildContext context) => MediaQuery.of(context).size.width >= 1100.0 && SizerUtil.deviceType != DeviceType.mobile && SizerUtil.deviceType == DeviceType.tablet;
@override
Widget build(BuildContext context) => LayoutBuilder(
builder: (context, constraints) => constraints.maxWidth >= 1100.0 && SizerUtil.deviceType != DeviceType.mobile && SizerUtil.deviceType != DeviceType.tablet
? desktop
: constraints.maxWidth < 1100.0 && constraints.maxWidth >= 600.0 && SizerUtil.deviceType == DeviceType.tablet
? tablet
: mobile,
);
}
Feel free to leave a comment if you need more information.
How to make a responsive widget? I would appreciate any help. Thank you in advance!
4
Answers
Use
Sizer
widget on top of MaterialApp to initialize it. Like the doc example,I will follow
try to Do It like package official example.
https://github.com/TechnoUrmish/Sizer/blob/master/example/lib/main.dart
If you don’t want to use any third party library then you can use
LayoutBuilder
.or you can use
Sizer
library.Link
In order to use
SizerUtil.deviceType
you must wrap the parent widget of your app with theSizer
widget. To make your app responsive, you can use thew
,h
, andsp
extensions functions provided with the sizer package. These functions allow you creation widget and fonts in proportion to the screen size. For example:In the above, if the device is a tablet, the Container takes up 100% (
100.w
) of the widget and 50% (50.h
) of the height. Else, the Container is sized differently.The
.sp
extension works similarly except that it’s for fonts.