How do you ensure that a specified theme is used?

I’ve defined a simple theme and am trying to use it, but it seems the default is being used. How do I ensure that the theme I specify (based on light blue) is used rather than the built-in purple default? This app

import 'package:flutter/material.dart';

void main() {
  runApp(ExampleApp());
}

class ExampleApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.lightBlue),
        textTheme: TextTheme(
          displayLarge: const TextStyle(
            fontSize: 72,
            fontWeight: FontWeight.bold,
          ),
        ),
      ),
      home: Scaffold(
        appBar: AppBar(
          backgroundColor: Theme.of(context).colorScheme.inversePrimary,
          title: Text('My Spiffy App'),
        ),
        body: ElevatedButton(
          onPressed: () {},
          style: ElevatedButton.styleFrom(
            backgroundColor: Theme.of(context).colorScheme.primary,
            foregroundColor: Colors.white, // text color
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(8),
            ),
          ),
          child: Text('My Spiffy Button', style: TextStyle(fontSize: 18)),
        ),
      ),
    );
  }
}

gives the rendering


I guess it’s because it’s using the context passed to the build method, so what’s the best way to restructure things to get the light blue theme from the get-go?

1 Like

In the example case the Scaffold is still using the the same context as the MaterialApp, which still uses the default Material theme. The theme you define is not available in the same context, only in contexts below it.

To see the custom theme defined in this example, wrap Scaffold with a Builder, or extract it to its own widget. I recommend the latter.

Also if you always want the ElevatedButton to have the style in the Scaffold, consider including it in your theme.

To do so, make a theme function in own file that returns your ThemeData object. In it, first create the desired ColorScheme object, pass it in to the ThemeData object you make and maybe also setup a bunch of helper functions that returns each custom component theme you want to define, pass them the same ColorScheme object so you can work with the same colors in them.

Your color scheme of context won’t be available until after you have made your theme, but to make custom component themes using the same ColorScheme colors as it will contain, you will need to create and use the same object in your component themes.

You can make various helpers and const tokens for the component theme definitions as well, that you want to share among them, typically shapes.

2 Likes