Repository navigation
Open
Description
Issue Description
When using flutter_screenutil with device_preview, the MediaQueryData may not be updated correctly, causing widgets to use the physical device's dimensions instead of the preview dimensions. This can be resolved by configuring ScreenUtil correctly.
Solution
Ensure ScreenUtil.configure is used to update the MediaQueryData within the ScreenUtilInit builder. Here's an example:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
FlutterNativeSplash.preserve(widgetsBinding: WidgetsFlutterBinding.ensureInitialized());
await App.onInit();
await App.session.close();
App.session.fetch().then((value) => FlutterNativeSplash.remove());
runApp(
DevicePreview(
enabled: App.device.isWeb || App.device.isIPad,
builder: (context) {
return ScreenUtilInit(
designSize: const Size(360, 690),
minTextAdapt: true,
splitScreenMode: true,
useInheritedMediaQuery: true,
builder: (context, child) {
ScreenUtil.configure(
data: MediaQuery.of(context),
);
return const EzStore();
},
);
},
),
);
}
class EzStore extends StatelessWidget {
const EzStore({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp.router(
builder: (context, child) {
return DevicePreview.appBuilder(context, child!);
},
title: 'EZ Store',
routerConfig: appRouter,
debugShowCheckedModeBanner: false,
theme: AppMaterialTheme(createTextTheme(context, "Montserrat", "Montserrat Alternates")).light(),
darkTheme: AppMaterialTheme(createTextTheme(context, "Montserrat", "Montserrat Alternates")).dark(),
);
}
}Additional Information
This ensures the MediaQueryData from device_preview is used correctly by ScreenUtil.
References
flutter doctor
[✓] Flutter (Channel stable, 3.22.2, on macOS 14.5 23F79 darwin-arm64, locale pt-BR)
[✓] Android toolchain - develop for Android devices (Android SDK version 34.0.0)
[✓] Xcode - develop for iOS and macOS (Xcode 15.4)
[✓] Chrome - develop for the web
[✓] Android Studio (version 2023.2)
[✓] IntelliJ IDEA Ultimate Edition (version 2024.1)
[✓] VS Code (version 1.91.0)
[✓] Connected device (5 available)
[✓] Network resourcesflutter_screenutil: ^5.9.3
device_preview: ^1.2.0
I hope it helps
Reacted by Alain Cruz Jiménez, Eleonor Menendez, Marcin Hradowicz, Abd Alazeez, Ahmed Hussein , Phillipp Bertram and kushagragupta-baynine
Metadata
Metadata
Assignees
Labels
No labels
Activity
alaincruz06 commentedon Nov 19, 2024
Thanks @paulocagol, although your code snippet helped me, I still have to do a hot-restart so the changes update (correctly on every preview-ed device). But it's still better than before.
ellie-me commentedon Nov 27, 2024
Thank you for this code snippet, it saved my life.
MahmoudElgaml commentedon Dec 13, 2024
what for the font size (sp) its not working with device preview ?
namtudev commentedon Mar 4, 2025
Some widgets don’t update when the device model changes in DevicePreview. Use this to force a rebuild:
Apply it inside ScreenUtilInit: