Skip to content

Instantly share code, notes, and snippets.

@ardera
Created November 8, 2019 00:48
Show Gist options
  • Save ardera/25a8c81a54fb37b0dc750d383caac5d9 to your computer and use it in GitHub Desktop.
Save ardera/25a8c81a54fb37b0dc750d383caac5d9 to your computer and use it in GitHub Desktop.
A simple flutter widget that can simulate/fake a different pixel ratio for all it's children. Can be the root widget, i.e. the widget given to runApp(). Useful for when your device/emulator doesn't properly calculate the devicePixelRatio.
import 'package:flutter/widgets.dart';
class FakeDevicePixelRatio extends StatelessWidget {
final num fakeDevicePixelRatio;
final Widget child;
FakeDevicePixelRatio({this.fakeDevicePixelRatio, this.child}) : assert(fakeDevicePixelRatio != null);
@override
Widget build(BuildContext context) {
final ratio = fakeDevicePixelRatio / WidgetsBinding.instance.window.devicePixelRatio;
return FractionallySizedBox(
widthFactor: 1/ratio,
heightFactor: 1/ratio,
child: Transform.scale(
scale: ratio,
child: child
)
);
}
}
@ltOgt
Copy link

ltOgt commented May 25, 2024

Thanks for sharing!

updated it to work with current version:

class _FakeDevicePixelRatio extends StatelessWidget {
  final num fakeDevicePixelRatio;
  final Widget child;

  const _FakeDevicePixelRatio({
    required this.fakeDevicePixelRatio,
    required this.child,
  });

  @override
  Widget build(BuildContext context) {
    final ratio = fakeDevicePixelRatio / MediaQuery.of(context).devicePixelRatio;

    return FractionallySizedBox(
      widthFactor: 1 / ratio,
      heightFactor: 1 / ratio,
      child: Transform.scale(
        scale: ratio,
        child: child,
      ),
    );
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment