62

I might very well be missing something as I'm so new to flutter, but I'm finding ThemeData's options very limited (at least with my understanding of how to implement it).

If you look at this random design below from MaterialUp, I'd want to model something roughly like:

Themedata.cyclingColor = Color.pink; ThemeData.runningColor = Color.green;

That way everywhere in my app I can reference cycling, running, swimming, gym colors (Or whatever colors make sense in the context of my app/design) and keep things consistent.

Random design from MaterialUp

Is there a recommended way to achieve this currently in Flutter? What are my options?

2

12 Answers 12

29

I recommend this approach, which is simple, works with hot reload and can be easily extended to support switching between dark and light themes.

First create your own analog to ThemeData, let's call it AppThemeData:

class AppThemeData {
  final BorderRadius borderRadius = BorderRadius.circular(8);

  final Color colorYellow = Color(0xffffff00);
  final Color colorPrimary = Color(0xffabcdef);

  ThemeData get materialTheme {
    return ThemeData(
        primaryColor: colorPrimary
    );
  }
}

The materialTheme can be used whenever the standard ThemeData is needed.

Then create a widget called AppTheme, which provides an instance of AppThemeData using the provider package.

class AppTheme extends StatelessWidget {
  final Widget child;

  AppTheme({this.child});

  @override
  Widget build(BuildContext context) {
    final themeData = AppThemeData(context);
    return Provider.value(value: themeData, child: child);
  }
}

Finally, wrap the whole app with AppTheme. To access the theme you can call context.watch<AppThemeData>(). Or create this extension...

extension BuildContextExtension on BuildContext {
  AppThemeData get appTheme {
    return watch<AppThemeData>();
  }
}

... and use context.appTheme. I usually put final theme = context.appTheme; on the first line of the widget build method.

9
  • 1
    That is slick, I love the usage of provider. Totally fixed my issue!
    – Aaron B
    Commented Jul 29, 2020 at 3:37
  • Wait, you will generate new instance of ThemeData each time you call materialTheme. Commented Sep 2, 2020 at 8:47
  • @AlexSemeniuk Yes, but in practice it's only called once.
    – fhucho
    Commented Sep 2, 2020 at 11:20
  • 1
    @DanielDodd, How did you resolve the context issue? Commented Feb 26, 2021 at 10:17
  • 1
    Yeah I haven't ran it and a Flutter beginner but I don't understand how AppThemeData(context) works given there is no constructor defined that accepts context?
    – nanobar
    Commented Sep 12, 2021 at 22:28
29

Updated for null-safety

I've extended standard ThemeData class so that at any time one could access own theme fields like that:

Theme.of(context).own().errorShade

Or like that:

ownTheme(context).errorShade

A theme can be defined and extended with new fields as follows(via addOwn() called on a certain ThemeData instance):

final ThemeData lightTheme = ThemeData.light().copyWith(
    accentColor: Colors.grey.withAlpha(128),
    backgroundColor: Color.fromARGB(255, 255, 255, 255),
    textTheme: TextTheme(
      caption: TextStyle(
          fontSize: 17.0, fontFamily: 'Montserrat', color: Colors.black),
    ))
  ..addOwn(OwnThemeFields(
      errorShade: Color.fromARGB(240, 255, 200, 200),
      textBaloon: Color.fromARGB(240, 255, 200, 200)));

final ThemeData darkTheme = ThemeData.dark().copyWith( ...
...

Themes can be applied to MaterialApp widget in a conventional way:

MaterialApp(
...
  theme: lightTheme,
  darkTheme: darkTheme,
)

The idea is to put all custom fields required for theming in a separate class OwnThemeFields.

Then extend ThemeData class with 2 methods:

  1. addOwn() that connects a certain instance of ThemedData to OwnThemeFields instance
  2. own() that allows to lookup for own fields associated with the given theme data

Also ownTheme helper method can be created to shorten the extraction of own fields.

class OwnThemeFields {
  final Color? errorShade;
  final Color? textBaloon;

  const OwnThemeFields({Color? errorShade, Color? textBaloon})
      : this.errorShade = errorShade,
        this.textBaloon = textBaloon;

  factory OwnThemeFields.empty() {
    return OwnThemeFields(errorShade: Colors.black, textBaloon: Colors.black);
  }
}
    
extension ThemeDataExtensions on ThemeData {
  static Map<InputDecorationTheme, OwnThemeFields> _own = {};

  void addOwn(OwnThemeFields own) {
    _own[this.inputDecorationTheme] = own;
  }

  static OwnThemeFields? empty = null;

  OwnThemeFields own() {
    var o = _own[this.inputDecorationTheme];
    if (o == null) {
      if (empty == null) empty = OwnThemeFields.empty();
      o = empty;
    }
    return o!;
  }
}

OwnThemeFields ownTheme(BuildContext context) => Theme.of(context).own();

Complete source: https://github.com/maxim-saplin/dikt/blob/master/lib/ui/themes.dart

10
  • 1
    Great solution!
    – mixable
    Commented Jan 7, 2021 at 19:58
  • 1
    It does not change the colors upon switching themes in app unless you hot reload
    – Texv
    Commented Jan 11, 2021 at 13:46
  • 1
    @Maxim I love your solution but the only problem is lets say I have 2 different themedata variables and each have their own '..addOwn' function. When I change the theme in the app, the OwnThemeFields does not change but stays to a fixed color. Do you know a workaround please? Would be easier for me to explain through share screen
    – Texv
    Commented Jan 15, 2021 at 21:44
  • 1
    Smart solution. But need to be modified for Null safety
    – Mayvas
    Commented Oct 25, 2021 at 11:13
  • 2
    @MaximSaplin You rely on inputDecorationTheme to key the collection and nothing ensures that this won't be a constant one. I would suggest to rely on brightness instead (with a caveat comment in the code for the case if the brightness happens to be that same for both themes, the programmer should select something else).
    – Gábor
    Commented Jan 31, 2022 at 11:45
17

2022: Use ThemeExtensions introduced in flutter 3

Here's a link! to the medium article I wrote.

  1. Create your ThemeExtension class
import 'package:flutter/material.dart';

@immutable
class MyCardTheme extends ThemeExtension<MyCardTheme> {
  const MyCardTheme({
    this.background = Colors.white,
    this.shape = const RoundedRectangleBorder(
      borderRadius: BorderRadius.all(
        Radius.circular(8),
      ),
    ),
  });

  final Color background;
  final ShapeBorder shape;

  @override
  MyCardTheme copyWith({
    Color? background,
    ShapeBorder? shape,
  }) {
    return MyCardTheme(
      background: background ?? this.background,
      shape: shape ?? this.shape,
    );
  }

  @override
  MyCardTheme lerp(ThemeExtension<MyCardTheme>? other, double t) {
    if (other is! MyCardTheme) {
      return this;
    }
    return MyCardTheme(
      background: Color.lerp(background, other.background, t) ?? Colors.white,
      shape: ShapeBorder.lerp(shape, other.shape, t) ??
          const RoundedRectangleBorder(
            borderRadius: BorderRadius.all(
              Radius.circular(8),
            ),
          ),
    );
  }

  @override
  String toString() => 'MyCardTheme('
      'background: $background, radius: $shape'
      ')';
}
  1. Create dark and light themes as per requirements
MyCardTheme lightCardTheme = MyCardTheme(
  background: Colors.blueGrey[200]!,
  shape: const RoundedRectangleBorder(
    borderRadius: BorderRadius.all(
      Radius.circular(24),
    ),
  ),
);

MyCardTheme darkCardTheme = MyCardTheme(
  background: Colors.blueGrey[800]!,
  shape: const RoundedRectangleBorder(
    borderRadius: BorderRadius.all(
      Radius.circular(24),
    ),
  ),
);
  1. Add extensions to your ThemeData for both, light and dark themes.
 theme: ThemeData(
    primarySwatch: Colors.green,
    cardTheme: const CardTheme(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.all(
          Radius.circular(8),
        ),
      ),
      color: Colors.green,
    ),
    extensions: <ThemeExtension<dynamic>>[
      lightCardTheme,
    ],
  ),
  darkTheme: ThemeData(
    brightness: Brightness.dark,
    primarySwatch: Colors.green,
    cardTheme: const CardTheme(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.all(
          Radius.circular(8),
        ),
      ),
      color: Colors.green,
    ),
    extensions: <ThemeExtension<dynamic>>[
      darkCardTheme,
    ],
  ),
  1. Use them in your build methods
final MyCardTheme customCardTheme =
        Theme.of(context).extension<MyCardTheme>()!;
Card(
    shape: customCardTheme.shape,
    color: customCardTheme.background,
    child: Container(
             padding: const EdgeInsets.all(16),
             child: const Text('Card styled from custom theme')),
          ),
    ),

1
  • Thanks, this is great! Using ThemeExtensions is much cleaner than some of the hackier methods of doing it!
    – VincentH
    Commented Apr 9, 2023 at 12:36
10

Instead of extending, you can use the new feature ThemeExtension in flutter. We can add custom styling and even use class type theme configuration in css.

example:


import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';

@immutable
class MyColors extends ThemeExtension<MyColors> {
  const MyColors({
    required this.brandColor,
    required this.danger,
  });

  final Color? brandColor;
  final Color? danger;

  @override
  MyColors copyWith({Color? brandColor, Color? danger}) {
    return MyColors(
      brandColor: brandColor ?? this.brandColor,
      danger: danger ?? this.danger,
    );
  }

  @override
  MyColors lerp(ThemeExtension<MyColors>? other, double t) {
    if (other is! MyColors) {
      return this;
    }
    return MyColors(
      brandColor: Color.lerp(brandColor, other.brandColor, t),
      danger: Color.lerp(danger, other.danger, t),
    );
  }

  // Optional
  @override
  String toString() => 'MyColors(brandColor: $brandColor, danger: $danger)';
}

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(
            brandColor: Color(0xFF1E88E5),
            danger: Color(0xFFE53935),
          ),
        ],
      ),
      darkTheme: ThemeData.dark().copyWith(
        extensions: <ThemeExtension<dynamic>>[
          const MyColors(
            brandColor: Color(0xFF90CAF9),
            danger: 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.brandColor),
          const SizedBox(width: 10),
          Container(width: 100, height: 100, color: myColors.danger),
          const SizedBox(width: 50),
          IconButton(
            icon: Icon(isLightTheme ? Icons.nightlight : Icons.wb_sunny),
            onPressed: toggleTheme,
          ),
        ],
      )),
    );
  }
}

from Flutter API Documentation

7

You can't extend ThemeData because then material components won't find it anymore.

You can just create and provide MyThemeData in addition to the ThemeData included in Flutter the same way.

Create a widget CustomThemeWidget that extends InheritedWidget and provide your custom theme there.

When you want to get a value from the current theme use

myTheme = CustomThemeWidget.of(context).myTheme;

To change the current theme change the MyThemeData in CustomThemeWidget.myTheme

Update

Like shown in https://github.com/flutter/flutter/pull/14793/files, it should be possible to extend ThemeData and provide it as ThemeData by overriding runtimeType

See also the comment in https://github.com/flutter/flutter/issues/16487#event-1573761656

7
  • Interesting idea. How would we get a custom type into that map with another type as key? Commented Mar 8, 2018 at 12:58
  • I think I get it now. You want to make a custom InheritedWidget that supports that use case. Sounds like a great idea. Commented Mar 8, 2018 at 13:08
  • 1
    Sounds promising :) Commented Mar 8, 2018 at 13:30
  • Sorry, I have to prepare for a meeting Commented Mar 8, 2018 at 14:38
  • 1
    Bad luck the solution you updated github.com/flutter/flutter/pull/14793/files, Never been merged.
    – kitta
    Commented Sep 12, 2020 at 10:53
5

Dart 2.7 later, extension support

you can add extension for system class

only add instance property is easy, but if you would get a dynamic color

you need think about it. for example, Use a constant to get the colors in light and dark modes

Determine if it is dark mode

two ways

  • MediaQuery.of(context).platformBrightnes == Brightness.dark;
  • Theme.of(context).brightness == Brightness.dark;

As you can see, you need the context, the context

Add Extension for BuildContext

Here is the code

extension MYContext on BuildContext {
  Color dynamicColor({int light, int dark}) {
    return (Theme.of(this).brightness == Brightness.light)
        ? Color(light)
        : Color(dark);
  }

  Color dynamicColour({Color light, Color dark}) {
    return (Theme.of(this).brightness == Brightness.light)
        ? light
        : dark;
  }

  /// the white background
  Color get bgWhite => dynamicColor(light: 0xFFFFFFFF, dark: 0xFF000000);
}

How to use

import 'package:flutter/material.dart';
import 'buildcontext_extension.dart';

class Test extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      color: context.bgWhite,
    );
  }
}

Also

This color may require multiple files, so you can create a public.dart file to manage it all

Like This

public.dart


library public;

// Export some common header files

// extensions
export 'buildcontext_extension.dart';

DarkMode images support

Put the light images in the same category as the dark ones

some code

static String getImgPath(String name, {
    String folder = '', 
    String format = 'png', 
    bool isDark = false, 
    bool needDark = true
  }) {
    String finalImagePath;
    if (needDark) {
      final folderName = isDark ? '${folder}_dark' : folder;
      finalImagePath = 'assets/images/$folderName/$name.$format';
    } else {
      finalImagePath = 'assets/images/$folder/$name.$format';
    }
    String isDarkPath = isDark ? "🌙 DarkMode" : "🌞 LightMode";
    print('$isDarkPath imagePath 🖼 $finalImagePath');
    return finalImagePath;
  }

2
  • I'd like your approach. Commented May 3, 2022 at 11:04
  • It's absolutely ugly way. Context object is not some sort of "app context" (like the one might think), it's a pointer to current element in an element tree. It shouldn't have any unrelated data. Commented Jan 12, 2023 at 19:17
5

I have also found that the ThemeData is restricting. What I have done, and will be doing for all of my apps in the future is creating my own ThemeData.

I have created a file named color_themes.dart and created a class named ColorThemes with constructors with the name of the colors that I desire. such as cyclingColor;

class ColorThemes {
    static const cyclingColor = const Color(0xffb74093); 
}

You can then call these colors by importing the file and calling ColorThemes.cyclingColor You can assign these values within your ThemeData to have these colors default to your ColorThemes. One of the benefits with using this method is that you do not need to use/reference context like so ThemeData.of(context) making it a lot easier to use your code in extracted widgets.

2
  • 1
    how about switching themes in the app in runtime? Commented Jan 19, 2020 at 7:41
  • 5
    Then, you avoid the benefits of multiple theming, the dark mode as well. Commented Jan 29, 2020 at 10:14
4

I solved this problem also for multiple themes by creating a CustomThemeData class like this:

class CustomThemeData {
    final double imageSize;

    CustomThemeData({
        this.imageSize = 100,
    });
}

Then, creating instances for each Theme:

final _customTheme = CustomThemeData(imageSize: 150);
final _customDarkTheme = CustomThemeData();

And writing an extension on ThemeData:

extension CustomTheme on ThemeData {
    CustomThemeData get custom => brightness == Brightness.dark ? _customDarkTheme : _customTheme;
}

Finally, the value can be accessed like this:

Theme.of(context).custom.imageSize

For more information see: https://bettercoding.dev/flutter/tutorial-themes-riverpod/#custom_attributes_extending_themedata

3
  • Thanks for this. Just clarifying, would this allow for multiple different themes that the user can select between manually, eg. a red theme, blue theme, dark theme, black theme? Or does it just allow for light and dark themes? Commented Sep 8, 2021 at 17:00
  • Unfortunately, Flutter only supports dark and light themes out of the box (by using theme and darkThemeof MaterialApp). You could set the theme dynamically (e.g. using a StateNotifierProvider), but then the solution would be far more complicated. Commented Sep 12, 2021 at 5:06
  • this was exactly the solution I was looking for, thank you
    – Jacoo
    Commented Jun 9, 2022 at 9:57
3

use this lib adaptive_theme for theme switch. And create extension of ColorSheme

extension MenuColorScheme on ColorScheme {
      Color get menuBackground => brightness == Brightness.light
          ? InlLightColors.White
          : InlDarkColors.Black;
}

In widget use that

Container(
      color: Theme.of(context).colorScheme.menuBackground,
...
)

This way is very simple and elegance. Nice to codding.

1

A simple workaround if you are not using all the textTheme headlines you can set some colors of some of them and use them like you normally use other colors.

set the headline1 color: ThemeData(textTheme: TextTheme(headline1: TextStyle(color: Colors.red),),),

Use it: RawMaterialButton(fillColor: Theme.of(context).textTheme.headline1.color,onPressed: onPressed,)

0

I created an implementation analog to the implementation of ThemeData:

@override
Widget build(BuildContext context) {
     final Brightness platformBrightness = Theme.of(context).brightness;
     final bool darkTheme = platformBrightness == Brightness.dark;

     return CustomAppTheme(
               customAppTheme:
                   darkTheme ? CustomAppThemeData.dark : CustomAppThemeData.light,
               child: Icon(Icons.add, color: CustomAppTheme.of(context).addColor,),
     );
}
import 'package:calendarflutter/style/custom_app_theme_data.dart';
import 'package:flutter/material.dart';

class CustomAppTheme extends InheritedWidget {
  CustomAppTheme({
    Key key,
    @required Widget child,
    this.customAppTheme,
  }) : super(key: key, child: child);

  final CustomAppThemeData customAppTheme;

  static CustomAppThemeData of(BuildContext context) {
    return context
        .dependOnInheritedWidgetOfExactType<CustomAppTheme>()
        .customAppTheme;
  }

  @override
  bool updateShouldNotify(CustomAppTheme oldWidget) =>
      customAppTheme != oldWidget.customAppTheme;
}
import 'package:flutter/material.dart';

class CustomAppThemeData {
  final Color plusColor;

  const CustomAppThemeData({
    @required this.plusColor,
  });

  static CustomAppThemeData get dark {
    return CustomAppThemeData(
      plusColor: Colors.red,
    );
  }

  static CustomAppThemeData get light {
    return CustomAppThemeData(
      plusColor: Colors.green,
    );
  }
}
1
  • I go into a little more detail in my blog post: www.felixlarsen.com/blog/custom-themedata-flutter-extension
    – i4guar
    Commented Mar 8, 2021 at 20:11
0

To extend (pun not intended) the answer of Maxim Saplin:

You may encounter a problem, where theme stays on the last one initialized in your code. This is happening because InputDecorationTheme is always the same for all of yours themes.

What solved it for me, was changing key (InputDecorationTheme) in _own to something unique, like themeID (you'll have to implement it somehow).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.