Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
d510dfd
first pass
guidezpl Feb 8, 2022
636ac9b
x
guidezpl Feb 8, 2022
b77306d
x
guidezpl Feb 8, 2022
1f35122
address feedback
guidezpl Feb 15, 2022
a379824
support multiple extensions
guidezpl Mar 1, 2022
000a674
add convenience function, Object ⇒ dynamic, lerping
guidezpl Mar 1, 2022
0578ca3
remove not-useful comment
guidezpl Mar 1, 2022
974888a
Merge remote-tracking branch 'upstream/master' into themedata_extensions
guidezpl Mar 1, 2022
707e2b1
fix examples/api lower sdk constraint
guidezpl Mar 1, 2022
839439e
remove trailing spaces
guidezpl Mar 1, 2022
9178aa2
remove another pesky trailing space
guidezpl Mar 1, 2022
6de9338
improve lerp
guidezpl Mar 1, 2022
1285ceb
Merge remote-tracking branch 'upstream/master' into themedata_extensions
guidezpl Mar 9, 2022
39bef30
address feedback
guidezpl Mar 9, 2022
a6994af
hide map implementation from constructor and copyWith
guidezpl Mar 9, 2022
de98b4e
use iterableproperty
guidezpl Mar 9, 2022
34156af
Revert "hide map implementation from constructor and copyWith"
guidezpl Mar 16, 2022
4812192
slow down sample
guidezpl Mar 16, 2022
7dc6caf
make theme extension params required
guidezpl Mar 16, 2022
6322352
add null check
guidezpl Mar 16, 2022
763eba3
improve documentation
guidezpl Mar 16, 2022
11ea6fe
fix hashCode and operator == overrides
guidezpl Mar 16, 2022
5c2a4e8
modify existing tests
guidezpl Mar 16, 2022
973902b
remove trailing spaces
guidezpl Mar 16, 2022
9a26dd7
add all tests except lerping
guidezpl Mar 16, 2022
4478749
fix lerping bug
guidezpl Mar 16, 2022
e7e1b2b
add toString to themeExtension example
guidezpl Mar 16, 2022
4a36393
add lerping test
guidezpl Mar 16, 2022
9349f4a
Merge branch 'flutter:master' into themedata_extensions
guidezpl Mar 16, 2022
46b5f30
assume non-nullability in example
guidezpl Mar 16, 2022
1f2baf8
address feedback
guidezpl Mar 17, 2022
886a31e
update docs
guidezpl Mar 17, 2022
8b7054e
remove trailing space
guidezpl Mar 17, 2022
004a92b
use Map.unmodifiable
guidezpl Mar 21, 2022
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
126 changes: 126 additions & 0 deletions examples/api/lib/material/theme/theme_extension.1.dart
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(
Copy link
Contributor

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.

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,
),
],
)
),
);
}
}
2 changes: 1 addition & 1 deletion examples/api/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ publish_to: 'none'
version: 1.0.0

environment:
sdk: ">=2.14.0-383.0.dev <3.0.0"
sdk: ">=2.17.0-0 <3.0.0"
flutter: ">=2.5.0-6.0.pre.30 <3.0.0"

dependencies:
Expand Down
96 changes: 96 additions & 0 deletions packages/flutter/lib/src/material/theme_data.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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.
///
/// {@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
Expand Down Expand Up @@ -242,6 +272,7 @@ class ThemeData with Diagnosticable {
AndroidOverscrollIndicator? androidOverscrollIndicator,
bool? applyElevationOverlayColor,
NoDefaultCupertinoThemeData? cupertinoOverrideTheme,
Iterable<ThemeExtension<dynamic>>? extensions,
InputDecorationTheme? inputDecorationTheme,
MaterialTapTargetSize? materialTapTargetSize,
PageTransitionsTheme? pageTransitionsTheme,
Expand Down Expand Up @@ -389,6 +420,7 @@ class ThemeData with Diagnosticable {
}) {
// GENERAL CONFIGURATION
cupertinoOverrideTheme = cupertinoOverrideTheme?.noDefault();
extensions ??= <ThemeExtension<dynamic>>[];
inputDecorationTheme ??= const InputDecorationTheme();
platform ??= defaultTargetPlatform;
switch (platform) {
Expand Down Expand Up @@ -560,6 +592,7 @@ class ThemeData with Diagnosticable {
androidOverscrollIndicator: androidOverscrollIndicator,
applyElevationOverlayColor: applyElevationOverlayColor,
cupertinoOverrideTheme: cupertinoOverrideTheme,
extensions: _themeExtensionIterableToMap(extensions),
inputDecorationTheme: inputDecorationTheme,
materialTapTargetSize: materialTapTargetSize,
pageTransitionsTheme: pageTransitionsTheme,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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),
Expand Down Expand Up @@ -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;
Copy link
Contributor

Choose a reason for hiding this comment

The 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.
///
Expand Down Expand Up @@ -1573,6 +1634,7 @@ class ThemeData with Diagnosticable {
AndroidOverscrollIndicator? androidOverscrollIndicator,
bool? applyElevationOverlayColor,
NoDefaultCupertinoThemeData? cupertinoOverrideTheme,
Iterable<ThemeExtension<dynamic>>? extensions,
InputDecorationTheme? inputDecorationTheme,
MaterialTapTargetSize? materialTapTargetSize,
PageTransitionsTheme? pageTransitionsTheme,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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.
Expand All @@ -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,
Expand Down Expand Up @@ -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 &&
Expand Down Expand Up @@ -2088,6 +2181,8 @@ class ThemeData with Diagnosticable {
androidOverscrollIndicator,
applyElevationOverlayColor,
cupertinoOverrideTheme,
hashList(extensions.keys),
hashList(extensions.values),
inputDecorationTheme,
materialTapTargetSize,
pageTransitionsTheme,
Expand Down Expand Up @@ -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));
Expand Down
Loading