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!