Last active
May 19, 2024 13:41
-
-
Save snapsl/31f1a4bae46c2436ca258cd6f3d71d68 to your computer and use it in GitHub Desktop.
Window class matching material 3 guidelines.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/widgets.dart' | |
show BoxConstraints, BuildContext, MediaQuery; | |
/// BoxConstraints matching the material3 guidelines | |
const BoxConstraints materialBoxConstraints = BoxConstraints(maxWidth: 840); | |
/// https://m3.material.io/foundations/layout/applying-layout/window-size-classes | |
enum WindowClass implements Comparable<WindowClass> { | |
small(_smallWidth), | |
medium(_mediumWidth), | |
expanded(_expandedWidth), | |
large(_largeWidth), | |
extraLarge(_extraLargeWidth); | |
static const double _smallWidth = 600; | |
static const double _mediumWidth = 840; | |
static const double _expandedWidth = 1200; | |
static const double _largeWidth = 1600; | |
static const double _extraLargeWidth = double.infinity; | |
final double maxWidth; | |
const WindowClass(this.maxWidth); | |
bool operator <(WindowClass other) => maxWidth < other.maxWidth; | |
bool operator <=(WindowClass other) => maxWidth <= other.maxWidth; | |
bool operator >(WindowClass other) => maxWidth > other.maxWidth; | |
bool operator >=(WindowClass other) => maxWidth >= other.maxWidth; | |
@override | |
int compareTo(WindowClass other) => maxWidth.compareTo(other.maxWidth); | |
/// This function returns the matching WindowClass given the current BuildContext. | |
/// | |
/// Usage: | |
/// ```dart | |
/// final windowClass = WindowClass.of(context); | |
/// | |
/// if (windowClass < WindowClass.medium) { | |
/// doSomeThing(); | |
/// } | |
/// ``` | |
static WindowClass of(BuildContext context) { | |
final screenWidth = MediaQuery.sizeOf(context).width; | |
return switch (screenWidth) { | |
< _smallWidth => WindowClass.small, | |
< _mediumWidth => WindowClass.medium, | |
< _expandedWidth => WindowClass.expanded, | |
< _largeWidth => WindowClass.large, | |
_ => WindowClass.extraLarge, | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment