如何在独立theme.dart文件的FloatingActionButtonThemeData中使用自定义ColorScheme内的颜色?
Perfect approach keeping all theme configs centralized! Since you’ve already defined your colorScheme as a constant in the same file, you don’t need to depend on Theme.of(context) to access its colors—you can directly reference the scheme’s properties right in your FloatingActionButtonThemeData definition.
Here’s how to update your code to make this work:
import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; const ColorScheme colorScheme = ColorScheme( primary: Color.fromRGBO(48, 48, 48, 1), primaryVariant: Color.fromRGBO(38, 38, 38, 1), onPrimary: Colors.white, secondary: Color.fromRGBO(232, 163, 72, 1), secondaryVariant: Color.fromRGBO(168, 121, 59, 1), onSecondary: Colors.white, surface: Colors.white, onSurface: Color.fromRGBO(48, 48, 48, 1), background: Colors.white, onBackground: Color.fromRGBO(48, 48, 48, 1), error: Color.fromRGBO(214, 84, 84, 1), onError: Colors.white, brightness: Brightness.light, ); const FloatingActionButtonThemeData fabTheme = FloatingActionButtonThemeData( // Directly use colors from your pre-defined colorScheme backgroundColor: colorScheme.secondary, foregroundColor: colorScheme.onSecondary, // Add any other properties you need (elevation, shape, etc.) );
Why this works:
- Your
colorSchemeis a top-level constant in the same file, so it’s accessible anywhere in the file without needing aBuildContext. - This keeps all your theme-related values tightly coupled and organized in one place, exactly what you’re aiming for.
- When you pass both your
colorSchemeandfabThemeto your app’sThemeData(e.g.,ThemeData(colorScheme: colorScheme, floatingActionButtonTheme: fabTheme)), all components will use consistent colors from your defined scheme.
If you later add dark mode support, you can just define a darkColorScheme constant and a corresponding darkFabTheme that references it—keeping everything neatly centralized.
内容的提问来源于stack exchange,提问作者Ishaan
相关产品推荐
相关产品推荐

