-
Notifications
You must be signed in to change notification settings - Fork 29.7k
Introduce Theme extensions #98033
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Introduce Theme extensions #98033
Changes from all commits
Commits
Show all changes
34 commits
Select commit
Hold shift + click to select a range
d510dfd
first pass
guidezpl 636ac9b
x
guidezpl b77306d
x
guidezpl 1f35122
address feedback
guidezpl a379824
support multiple extensions
guidezpl 000a674
add convenience function, Object ⇒ dynamic, lerping
guidezpl 0578ca3
remove not-useful comment
guidezpl 974888a
Merge remote-tracking branch 'upstream/master' into themedata_extensions
guidezpl 707e2b1
fix examples/api lower sdk constraint
guidezpl 839439e
remove trailing spaces
guidezpl 9178aa2
remove another pesky trailing space
guidezpl 6de9338
improve lerp
guidezpl 1285ceb
Merge remote-tracking branch 'upstream/master' into themedata_extensions
guidezpl 39bef30
address feedback
guidezpl a6994af
hide map implementation from constructor and copyWith
guidezpl de98b4e
use iterableproperty
guidezpl 34156af
Revert "hide map implementation from constructor and copyWith"
guidezpl 4812192
slow down sample
guidezpl 7dc6caf
make theme extension params required
guidezpl 6322352
add null check
guidezpl 763eba3
improve documentation
guidezpl 11ea6fe
fix hashCode and operator == overrides
guidezpl 5c2a4e8
modify existing tests
guidezpl 973902b
remove trailing spaces
guidezpl 9a26dd7
add all tests except lerping
guidezpl 4478749
fix lerping bug
guidezpl e7e1b2b
add toString to themeExtension example
guidezpl 4a36393
add lerping test
guidezpl 9349f4a
Merge branch 'flutter:master' into themedata_extensions
guidezpl 46b5f30
assume non-nullability in example
guidezpl 1f2baf8
address feedback
guidezpl 886a31e
update docs
guidezpl 8b7054e
remove trailing space
guidezpl 004a92b
use Map.unmodifiable
guidezpl File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,126 @@ | ||
| // Copyright 2014 The Flutter Authors. All rights reserved. | ||
| // Use of this source code is governed by a BSD-style license that can be | ||
| // found in the LICENSE file. | ||
|
|
||
| // Flutter code sample for ThemeExtension | ||
|
|
||
| import 'package:flutter/material.dart'; | ||
| import 'package:flutter/scheduler.dart'; | ||
|
|
||
| @immutable | ||
| class MyColors extends ThemeExtension<MyColors> { | ||
| const MyColors({ | ||
| required this.blue, | ||
| required this.red, | ||
| }); | ||
|
|
||
| final Color? blue; | ||
| final Color? red; | ||
|
|
||
| @override | ||
| MyColors copyWith({Color? red, Color? blue}) { | ||
| return MyColors( | ||
| blue: blue ?? this.blue, | ||
| red: red ?? this.red, | ||
| ); | ||
| } | ||
|
|
||
| @override | ||
| MyColors lerp(ThemeExtension<MyColors>? other, double t) { | ||
| if (other is! MyColors) { | ||
| return this; | ||
| } | ||
| return MyColors( | ||
| blue: Color.lerp(blue, other.blue, t), | ||
| red: Color.lerp(red, other.red, t), | ||
| ); | ||
| } | ||
|
|
||
| // Optional | ||
| @override | ||
| String toString() => 'MyColors(blue: $blue, red: $red)'; | ||
| } | ||
|
|
||
| void main() { | ||
| // Slow down time to see lerping. | ||
| timeDilation = 5.0; | ||
| runApp(const MyApp()); | ||
| } | ||
|
|
||
| class MyApp extends StatefulWidget { | ||
| const MyApp({Key? key}) : super(key: key); | ||
|
|
||
| static const String _title = 'Flutter Code Sample'; | ||
|
|
||
| @override | ||
| State<MyApp> createState() => _MyAppState(); | ||
| } | ||
|
|
||
| class _MyAppState extends State<MyApp> { | ||
| bool isLightTheme = true; | ||
|
|
||
| void toggleTheme() { | ||
| setState(() => isLightTheme = !isLightTheme); | ||
| } | ||
|
|
||
| @override | ||
| Widget build(BuildContext context) { | ||
| return MaterialApp( | ||
| title: MyApp._title, | ||
| theme: ThemeData.light().copyWith( | ||
| extensions: <ThemeExtension<dynamic>>{ | ||
| const MyColors( | ||
| blue: Color(0xFF1E88E5), | ||
| red: Color(0xFFE53935), | ||
| ), | ||
| }, | ||
| ), | ||
| darkTheme: ThemeData.dark().copyWith( | ||
| extensions: <ThemeExtension<dynamic>>{ | ||
| const MyColors( | ||
| blue: Color(0xFF90CAF9), | ||
| red: Color(0xFFEF9A9A), | ||
| ), | ||
| }, | ||
| ), | ||
| themeMode: isLightTheme ? ThemeMode.light : ThemeMode.dark, | ||
| home: Home( | ||
| isLightTheme: isLightTheme, | ||
| toggleTheme: toggleTheme, | ||
| ), | ||
| ); | ||
| } | ||
| } | ||
|
|
||
| class Home extends StatelessWidget { | ||
| const Home({ | ||
| Key? key, | ||
| required this.isLightTheme, | ||
| required this.toggleTheme, | ||
| }) : super(key: key); | ||
|
|
||
| final bool isLightTheme; | ||
| final void Function() toggleTheme; | ||
|
|
||
| @override | ||
| Widget build(BuildContext context) { | ||
| final MyColors myColors = Theme.of(context).extension<MyColors>()!; | ||
| return Material( | ||
| child: Center( | ||
| child: Row( | ||
| mainAxisAlignment: MainAxisAlignment.center, | ||
| children: <Widget>[ | ||
| Container(width: 100, height: 100, color: myColors.blue), | ||
| const SizedBox(width: 10), | ||
| Container(width: 100, height: 100, color: myColors.red), | ||
| const SizedBox(width: 50), | ||
| IconButton( | ||
| icon: Icon(isLightTheme ? Icons.nightlight : Icons.wb_sunny), | ||
| onPressed: toggleTheme, | ||
| ), | ||
| ], | ||
| ) | ||
| ), | ||
| ); | ||
| } | ||
| } | ||
This file contains hidden or 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
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -52,6 +52,36 @@ import 'typography.dart'; | |
|
|
||
| export 'package:flutter/services.dart' show Brightness; | ||
|
|
||
| /// An interface that defines custom additions to a [ThemeData] object. | ||
| /// | ||
| /// Typically used for custom colors. To use, subclass [ThemeExtension], | ||
| /// define a number of fields (e.g. [Color]s), and implement the [copyWith] and | ||
| /// [lerp] methods. The latter will ensure smooth transitions of properties when | ||
| /// switching themes. | ||
| /// | ||
guidezpl marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| /// {@tool dartpad} | ||
| /// This sample shows how to create and use a subclass of [ThemeExtension] that | ||
| /// defines two colors. | ||
| /// | ||
| /// ** See code in examples/api/lib/material/theme/theme_extension.1.dart ** | ||
| /// {@end-tool} | ||
| abstract class ThemeExtension<T extends ThemeExtension<T>> { | ||
| /// Enable const constructor for subclasses. | ||
| const ThemeExtension(); | ||
|
|
||
| /// The extension's type. | ||
| Object get type => T; | ||
|
|
||
| /// Creates a copy of this theme extension with the given fields | ||
| /// replaced by the non-null parameter values. | ||
| ThemeExtension<T> copyWith(); | ||
|
|
||
| /// Linearly interpolate with another [ThemeExtension] object. | ||
| /// | ||
| /// {@macro dart.ui.shadow.lerp} | ||
| ThemeExtension<T> lerp(ThemeExtension<T>? other, double t); | ||
| } | ||
|
|
||
| // Deriving these values is black magic. The spec claims that pressed buttons | ||
| // have a highlight of 0x66999999, but that's clearly wrong. The videos in the | ||
| // spec show that buttons have a composited highlight of #E1E1E1 on a background | ||
|
|
@@ -242,6 +272,7 @@ class ThemeData with Diagnosticable { | |
| AndroidOverscrollIndicator? androidOverscrollIndicator, | ||
| bool? applyElevationOverlayColor, | ||
| NoDefaultCupertinoThemeData? cupertinoOverrideTheme, | ||
| Iterable<ThemeExtension<dynamic>>? extensions, | ||
| InputDecorationTheme? inputDecorationTheme, | ||
| MaterialTapTargetSize? materialTapTargetSize, | ||
| PageTransitionsTheme? pageTransitionsTheme, | ||
|
|
@@ -389,6 +420,7 @@ class ThemeData with Diagnosticable { | |
| }) { | ||
| // GENERAL CONFIGURATION | ||
| cupertinoOverrideTheme = cupertinoOverrideTheme?.noDefault(); | ||
| extensions ??= <ThemeExtension<dynamic>>[]; | ||
| inputDecorationTheme ??= const InputDecorationTheme(); | ||
| platform ??= defaultTargetPlatform; | ||
| switch (platform) { | ||
|
|
@@ -560,6 +592,7 @@ class ThemeData with Diagnosticable { | |
| androidOverscrollIndicator: androidOverscrollIndicator, | ||
| applyElevationOverlayColor: applyElevationOverlayColor, | ||
| cupertinoOverrideTheme: cupertinoOverrideTheme, | ||
| extensions: _themeExtensionIterableToMap(extensions), | ||
| inputDecorationTheme: inputDecorationTheme, | ||
| materialTapTargetSize: materialTapTargetSize, | ||
| pageTransitionsTheme: pageTransitionsTheme, | ||
|
|
@@ -663,6 +696,7 @@ class ThemeData with Diagnosticable { | |
| required this.androidOverscrollIndicator, | ||
| required this.applyElevationOverlayColor, | ||
| required this.cupertinoOverrideTheme, | ||
| required this.extensions, | ||
| required this.inputDecorationTheme, | ||
| required this.materialTapTargetSize, | ||
| required this.pageTransitionsTheme, | ||
|
|
@@ -805,6 +839,7 @@ class ThemeData with Diagnosticable { | |
| required this.primaryColorBrightness, | ||
| }) : // GENERAL CONFIGURATION | ||
| assert(applyElevationOverlayColor != null), | ||
| assert(extensions != null), | ||
| assert(inputDecorationTheme != null), | ||
| assert(materialTapTargetSize != null), | ||
| assert(pageTransitionsTheme != null), | ||
|
|
@@ -1044,6 +1079,32 @@ class ThemeData with Diagnosticable { | |
| /// can be overridden using attributes of this [cupertinoOverrideTheme]. | ||
| final NoDefaultCupertinoThemeData? cupertinoOverrideTheme; | ||
|
|
||
| /// Arbitrary additions to this theme. | ||
| /// | ||
| /// To define extensions, pass an [Iterable] containing one or more [ThemeExtension] | ||
| /// subclasses to [ThemeData.new] or [copyWith]. | ||
| /// | ||
| /// To obtain an extension, use [extension]. | ||
| /// | ||
| /// {@tool dartpad} | ||
| /// This sample shows how to create and use a subclass of [ThemeExtension] that | ||
| /// defines two colors. | ||
| /// | ||
| /// ** See code in examples/api/lib/material/theme/theme_extension.1.dart ** | ||
| /// {@end-tool} | ||
| /// | ||
| /// See also: | ||
| /// | ||
| /// * [extension], a convenience function for obtaining a specific extension. | ||
| final Map<Object, ThemeExtension<dynamic>> extensions; | ||
|
|
||
| /// Used to obtain a particular [ThemeExtension] from [extensions]. | ||
| /// | ||
| /// Obtain with `Theme.of(context).extension<MyThemeExtension>()`. | ||
| /// | ||
| /// See [extensions] for an interactive example. | ||
| T? extension<T>() => extensions[T] as T; | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. NICE |
||
|
|
||
| /// The default [InputDecoration] values for [InputDecorator], [TextField], | ||
| /// and [TextFormField] are based on this theme. | ||
| /// | ||
|
|
@@ -1573,6 +1634,7 @@ class ThemeData with Diagnosticable { | |
| AndroidOverscrollIndicator? androidOverscrollIndicator, | ||
| bool? applyElevationOverlayColor, | ||
| NoDefaultCupertinoThemeData? cupertinoOverrideTheme, | ||
| Iterable<ThemeExtension<dynamic>>? extensions, | ||
| InputDecorationTheme? inputDecorationTheme, | ||
| MaterialTapTargetSize? materialTapTargetSize, | ||
| PageTransitionsTheme? pageTransitionsTheme, | ||
|
|
@@ -1721,6 +1783,7 @@ class ThemeData with Diagnosticable { | |
| androidOverscrollIndicator: androidOverscrollIndicator ?? this.androidOverscrollIndicator, | ||
| applyElevationOverlayColor: applyElevationOverlayColor ?? this.applyElevationOverlayColor, | ||
| cupertinoOverrideTheme: cupertinoOverrideTheme ?? this.cupertinoOverrideTheme, | ||
| extensions: (extensions != null) ? _themeExtensionIterableToMap(extensions) : this.extensions, | ||
| inputDecorationTheme: inputDecorationTheme ?? this.inputDecorationTheme, | ||
| materialTapTargetSize: materialTapTargetSize ?? this.materialTapTargetSize, | ||
| pageTransitionsTheme: pageTransitionsTheme ?? this.pageTransitionsTheme, | ||
|
|
@@ -1874,6 +1937,34 @@ class ThemeData with Diagnosticable { | |
| return Brightness.dark; | ||
| } | ||
|
|
||
| /// Linearly interpolate between two [extensions]. | ||
| /// | ||
| /// Includes all theme extensions in [a] and [b]. | ||
| /// | ||
| /// {@macro dart.ui.shadow.lerp} | ||
| static Map<Object, ThemeExtension<dynamic>> _lerpThemeExtensions(ThemeData a, ThemeData b, double t) { | ||
| // Lerp [a]. | ||
| final Map<Object, ThemeExtension<dynamic>> newExtensions = a.extensions.map((Object id, ThemeExtension<dynamic> extensionA) { | ||
| final ThemeExtension<dynamic>? extensionB = b.extensions[id]; | ||
| return MapEntry<Object, ThemeExtension<dynamic>>(id, extensionA.lerp(extensionB, t)); | ||
| }); | ||
| // Add [b]-only extensions. | ||
| newExtensions.addEntries(b.extensions.entries.where( | ||
| (MapEntry<Object, ThemeExtension<dynamic>> entry) => | ||
| !a.extensions.containsKey(entry.key))); | ||
|
|
||
| return newExtensions; | ||
| } | ||
|
|
||
| /// Convert the [extensionsIterable] passed to [ThemeData.new] or [copyWith] | ||
| /// to the stored [extensions] map, where each entry's key consists of the extension's type. | ||
| static Map<Object, ThemeExtension<dynamic>> _themeExtensionIterableToMap(Iterable<ThemeExtension<dynamic>> extensionsIterable) { | ||
| return Map<Object, ThemeExtension<dynamic>>.unmodifiable(<Object, ThemeExtension<dynamic>>{ | ||
| // Strangely, the cast is necessary for tests to run. | ||
| for (final ThemeExtension<dynamic> extension in extensionsIterable) extension.type: extension as ThemeExtension<ThemeExtension<dynamic>> | ||
| }); | ||
| } | ||
|
|
||
| /// Linearly interpolate between two themes. | ||
| /// | ||
| /// The arguments must not be null. | ||
|
|
@@ -1891,6 +1982,7 @@ class ThemeData with Diagnosticable { | |
| androidOverscrollIndicator:t < 0.5 ? a.androidOverscrollIndicator : b.androidOverscrollIndicator, | ||
| applyElevationOverlayColor:t < 0.5 ? a.applyElevationOverlayColor : b.applyElevationOverlayColor, | ||
| cupertinoOverrideTheme:t < 0.5 ? a.cupertinoOverrideTheme : b.cupertinoOverrideTheme, | ||
| extensions: _lerpThemeExtensions(a, b, t), | ||
| inputDecorationTheme:t < 0.5 ? a.inputDecorationTheme : b.inputDecorationTheme, | ||
| materialTapTargetSize:t < 0.5 ? a.materialTapTargetSize : b.materialTapTargetSize, | ||
| pageTransitionsTheme:t < 0.5 ? a.pageTransitionsTheme : b.pageTransitionsTheme, | ||
|
|
@@ -1991,6 +2083,7 @@ class ThemeData with Diagnosticable { | |
| other.androidOverscrollIndicator == androidOverscrollIndicator && | ||
| other.applyElevationOverlayColor == applyElevationOverlayColor && | ||
| other.cupertinoOverrideTheme == cupertinoOverrideTheme && | ||
| mapEquals(other.extensions, extensions) && | ||
| other.inputDecorationTheme == inputDecorationTheme && | ||
| other.materialTapTargetSize == materialTapTargetSize && | ||
| other.pageTransitionsTheme == pageTransitionsTheme && | ||
|
|
@@ -2088,6 +2181,8 @@ class ThemeData with Diagnosticable { | |
| androidOverscrollIndicator, | ||
| applyElevationOverlayColor, | ||
| cupertinoOverrideTheme, | ||
| hashList(extensions.keys), | ||
| hashList(extensions.values), | ||
| inputDecorationTheme, | ||
| materialTapTargetSize, | ||
| pageTransitionsTheme, | ||
|
|
@@ -2185,6 +2280,7 @@ class ThemeData with Diagnosticable { | |
| properties.add(EnumProperty<AndroidOverscrollIndicator>('androidOverscrollIndicator', androidOverscrollIndicator, defaultValue: null, level: DiagnosticLevel.debug)); | ||
| properties.add(DiagnosticsProperty<bool>('applyElevationOverlayColor', applyElevationOverlayColor, level: DiagnosticLevel.debug)); | ||
| properties.add(DiagnosticsProperty<NoDefaultCupertinoThemeData>('cupertinoOverrideTheme', cupertinoOverrideTheme, defaultValue: defaultData.cupertinoOverrideTheme, level: DiagnosticLevel.debug)); | ||
| properties.add(IterableProperty<ThemeExtension<dynamic>>('extensions', extensions.values, defaultValue: defaultData.extensions.values, level: DiagnosticLevel.debug)); | ||
| properties.add(DiagnosticsProperty<InputDecorationTheme>('inputDecorationTheme', inputDecorationTheme, level: DiagnosticLevel.debug)); | ||
| properties.add(DiagnosticsProperty<MaterialTapTargetSize>('materialTapTargetSize', materialTapTargetSize, level: DiagnosticLevel.debug)); | ||
| properties.add(DiagnosticsProperty<PageTransitionsTheme>('pageTransitionsTheme', pageTransitionsTheme, level: DiagnosticLevel.debug)); | ||
|
|
||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
NICE, thanks for including darkTheme in the example.