skip to Main Content

I want to set a color in my Theme to the primary color.
When the primary color changes, so should the other color.

I know how to assign a hardcoded color to any color in the Theme.
But I don’t know how to dynamically reference the primary color.

Here’s what I tried:

import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(
      theme: ThemeData(
        useMaterial3: true,
        textTheme: const TextTheme(titleLarge: TextStyle(color: Colors.black)),
      ),
      home: const MyHomePage(),
    ));

class MyHomePage extends StatelessWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Text('ok', style: Theme.of(context).textTheme.titleLarge),
    );
  }
}

Is it possible to refer primary color instead of setting black color?

2

Answers


  1. From the docs: https://docs.flutter.dev/cookbook/design/themes

    Theme(
      // Create a unique theme with `ThemeData`.
      data: ThemeData(
        colorScheme: ColorScheme.fromSeed(
          seedColor: Colors.pink,
        ),
      ),
    );
    

    Remember: As of the Flutter 3.16 release, Material 3 is Flutter’s default theme.

    Login or Signup to reply.
  2. You could create your own subclass of ThemeData and override the getter for the appropriate color to return the primary color instead.

    class CustomThemeData extends ThemeData
    {
      // Implement appropriate constructor or factory
      // ...
    
      // Then override getter to return the primary color
      @override
      Color get cardColor => this.primaryColor;
    }
    
    

    And use it when running your app

    void main() => runApp(MaterialApp(
      theme: CustomThemeData(
        useMaterial3: true,
        textTheme: const TextTheme(titleLarge: TextStyle(color: Colors.black)),
      ),
      home: const MyHomePage(),
    ));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search