Skip to content

Instantly share code, notes, and snippets.

@flutterdevrelgists
Created January 24, 2023 23:51
Show Gist options
  • Save flutterdevrelgists/f73b6a5d62b80821a598a25a675a98f2 to your computer and use it in GitHub Desktop.
Save flutterdevrelgists/f73b6a5d62b80821a598a25a675a98f2 to your computer and use it in GitHub Desktop.
Adaptive UI Talk: Example of handling light mode and dark mode in Cupertino.
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart' show Icons;
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
Brightness _brightness = Brightness.light;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
_brightness = WidgetsBinding.instance.window.platformBrightness;
}
@override
void didChangePlatformBrightness() {
if (mounted) {
setState(() {
_brightness = WidgetsBinding.instance.window.platformBrightness;
});
}
super.didChangePlatformBrightness();
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@override
Widget build(BuildContext context) {
return CupertinoApp(
debugShowCheckedModeBanner: false,
theme: CupertinoThemeData(
brightness: _brightness,
),
home: const CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
middle: Text('Flutter Forward 2023'),
),
child: _MyPage(),
),
);
}
}
class _MyPage extends StatelessWidget {
const _MyPage();
@override
Widget build(BuildContext context) {
return Center(
child: Icon(
CupertinoTheme.of(context).brightness == Brightness.light
? Icons.light_mode
: Icons.dark_mode,
color: const CupertinoDynamicColor.withBrightness(
color: CupertinoColors.black,
darkColor: CupertinoColors.white,
).resolveFrom(context),
size: 100.0,
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment