Flutter: How to Deal With Samsung Galaxy Fold
Some of you may be using flexible measurements for width, height, padding, margin, font size etc using MediaQuery.of(context).size or the sizer package. For what I’m about to describe below, the sizer package doesn’t work. I do think it’s a very nice, convenient package, but my stance on packages is that if you can make it yourself using what Flutter provides you — do it yourself, because that’s the only way you’ll progress as a developer.
Anyways, I have a Samsung Galaxy Fold3, and it’s been a source of stress for me, since I have to consider the fact that when it is opened up to its full size, the width is over 500 pixels. So, I’ve been using flexible size just for the Fold, such as below.
final double _width = MediaQuery.of(context).size.width;
final double _fontSize = _width > 400.0 ? 15.5 : 13.0;
Initially, when I open the phone to full size, the flexible sizing worked fine — However, after opening it to full size and then closing it (hence, putting the app in the background), then re-opening the app (put it in the foreground), such flexible size measurements did not work (ugh).
So, the simple solution (not a perfect one yet) that I’ve found is to use WidgetsBindingObserver mixin.
When WidgetsBindingObserver detects that the metrics changed, you can just set state the page to apply the flexible measurements. I put the set-state in addPostFrameCallback, because if not, the set-state happened while the page was being built. Right now, there is a slight problem that the initial page gets built first, and then gets set state, so you do see a slight error happening there.
Also, you would need this for every page that you think needs to be rebuilt. I don’t recommend putting it where it’s at the top level that connects to all pages because it would set-state all child pages which don’t need to be rebuilt at that moment (unless that’s what you want).
As I mentioned above, this method won’t work with the sizer package because (I’m guessing?) WidgetsBindingObserver deals with Flutter’s BuildContext directly, and it would require an extra step for that modification to be passed onto the sizer package (who knows).
WidgetsBinding.instance has a lot of other features you can use, like telling you what AppLifecycleState it is in, and you should explore them!