flutterdartfloating-action-buttonthemedata

Access ThemeData property inside ThemeData definition


In my Flutter app I declare ThemeData with a colorSchemeSeed:

return MaterialApp(
  ...
  theme: ThemeData(
    useMaterial3: true,
    visualDensity: VisualDensity.adaptivePlatformDensity,
    colorSchemeSeed: Colors.blueGrey,
    ...
    floatingActionButtonTheme: FloatingActionButtonThemeData(
      backgroundColor: ?
    ),
  ),
  ...
);

I would like to redefine the backgroundColor of the FloatingActionButton using tertiaryContainer color. Anywhere else in the code I can set this property to FloatingActionButton:

backgroundColor: Theme.of(context).colorScheme.tertiaryContainer,

However, I would like to redefine this property directly in the theme declaration, so that I don't have to do it everywhere and so that I don't define a widget on purpose.

It's possible to do it? If yes, in what way? Thanks in advance!


Solution

  • You can define a first variable theme and reuse it:

    final theme = ThemeData(
      useMaterial3: true,
      visualDensity: VisualDensity.adaptivePlatformDensity,
      colorSchemeSeed: Colors.blueGrey,
    );
    MaterialApp(
      return theme.copyWith(
        floatingActionButtonTheme: FloatingActionButtonThemeData(
          backgroundColor: theme.colorScheme.tertiaryContainer,
          ),
      ),
    );