You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在独立theme.dart文件的FloatingActionButtonThemeData中使用自定义ColorScheme内的颜色?

How to reference a local ColorScheme in FloatingActionButtonThemeData

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 colorScheme is a top-level constant in the same file, so it’s accessible anywhere in the file without needing a BuildContext.
  • 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 colorScheme and fabTheme to your app’s ThemeData (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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 09:47:37