Skip to content

Instantly share code, notes, and snippets.

@iqbalmineraltown
Last active December 18, 2019 03:13
Show Gist options
  • Save iqbalmineraltown/42a01890c3acf03031ecf3cb0710d05c to your computer and use it in GitHub Desktop.
Save iqbalmineraltown/42a01890c3acf03031ecf3cb0710d05c to your computer and use it in GitHub Desktop.
import 'package:flutter/material.dart';
final Color darkBlue = Color.fromARGB(255, 18, 32, 47);
// store as static reference within app lifecycle
int _devicePixelCategory;
// image samples, e.g. 1x to 4x
// assuming this list is sorted from lowest res
final List<String> _imageOptions = [
'source/to/image/SD',
'source/to/image/HD',
'source/to/image/FHD',
'source/to/image/UHD',
];
// create util function to be called on every image network request
String imageOptionSelector(List<String> imageOptions) {
// seems better using switch case
return imageOptions[_devicePixelCategory - 1];
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center(
child: MyWidget(),
),
),
);
}
}
class MyWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
// check device pixel once every app start
// devicePixelRatio (dpr) normally wont go lower than 1
// if devicePixelRatio is between 2 value, better serve higher res.
// E.g. devicePixelRatio 1.2 should serve 2x image, 2.1 serve 3x, etc
_devicePixelCategory ??= MediaQuery.of(context).devicePixelRatio.ceil();
var width = MediaQuery.of(context).size.width;
var height = MediaQuery.of(context).size.height;
return Text(
'Screen res $width x $height with devicePixelRatio ${MediaQuery.of(context).devicePixelRatio}\n serving ${imageOptionSelector(_imageOptions)}',
style: Theme.of(context).textTheme.display1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment