Last active
January 30, 2021 23:16
-
-
Save lukepighetti/074f505903e7ab5561da7e8e7fda04b2 to your computer and use it in GitHub Desktop.
A simple way to handle light/dark theme with animation tied to ThemeData.
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/material.dart'; | |
/// ```dart | |
/// class MyLightAndDarkThemeWidget extends StatelessWidget { | |
/// @override | |
/// Widget build(BuildContext context) { | |
/// return ThemeBrightnessAnimatedBuilder( | |
/// builder: (context, t, child) { | |
/// final lightThemeColor = Colors.red.shade800; | |
/// final darkThemeColor = Colors.red.shade200; | |
/// | |
/// return Container( | |
/// /// Light theme color goes on the right, dark theme on the left. | |
/// color: Color.lerp(lightThemeColor, darkThemeColor, t), | |
/// ); | |
/// }, | |
/// ); | |
/// } | |
/// } | |
/// ``` | |
class ThemeBrightnessAnimatedBuilder extends StatelessWidget { | |
/// A builder that automatically transitions t from `0.0` to `1.0` depending on if | |
/// [ThemeData.brightness] is [Brightness.dark] or [Brightness.light] | |
const ThemeBrightnessAnimatedBuilder({ | |
Key key, | |
@required this.builder, | |
this.child, | |
}) : super(key: key); | |
/// `0.0` when [ThemeData.brightness] is [Brightness.light] | |
/// `1.0` when [ThemeData.brightness] is [Brightness.dark] | |
final Widget Function(BuildContext, double, Widget) builder; | |
/// A child to pass through without rebuilding when animating. | |
final Widget child; | |
@override | |
Widget build(BuildContext context) { | |
final theme = Theme.of(context); | |
return TweenAnimationBuilder( | |
tween: Tween<double>(end: theme.brightness == Brightness.light ? 0 : 1), | |
curve: Curves.linear, | |
duration: kThemeAnimationDuration, | |
builder: builder, | |
child: child, | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment