Flutter: How to extend ThemeData

Problem

The way to extend ThemeData in Flutter has been a frequently asked question on StackOverflow: Is it possible “extend” ThemeData in Flutter.

There are even issues created in the Flutter official repository:

With dart 2.7, this is finally possible by using Extension methods.

Note

Solution

Let’s make a bootstrap flavored color scheme:

Image for post
Image for post

First of all, create a file custom_color_scheme.dart:

import 'package:flutter/material.dart';extension CustomColorScheme on ColorScheme {
Color get success => const Color(0xFF28a745);
Color get info => const Color(0xFF17a2b8);
Color get warning => const Color(0xFFffc107);
Color get danger => const Color(0xFFdc3545);
}

Then in your components, import this file, you will be able to use those color instantly.

import 'custom_color_scheme.dart';FlatButton(
color: Theme.of(context).colorScheme.success,
textColor: Colors.white,
child: const Text('Success'),
onPressed: () {},
)

Visit this repository to see the full example.

Drawbacks

Updates

As Pablo Pasqualino suggests that, we can actually work with light/dark brightness like this:

extension CustomColorScheme on ColorScheme {
Color get success => brightness == Brightness.light ? const Color(0xFF28a745) : const Color(0x2228a745);
}

Thanks Pablo!

Do you know you can clap up to 50 times for an article? Go give it a try!

A JavaScript/Node/Flutter developer who love technical stuffs.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store