Flutter ColorScheme未生效求助:自定义配色被默认蓝色主题覆盖
Flutter自定义主题不生效问题解决
你的问题确实和**上下文(context)**直接相关。当前代码里Theme.of(context)调用的是MyApp组件build方法的上下文,这个上下文是在MaterialApp创建之前的,根本拿不到你在MaterialApp里配置的自定义主题,只能读取Flutter默认的蓝色主题,所以才会出现颜色不对的情况。
下面给你两种可行的解决方法:
方法一:将首页内容抽成独立组件
把home参数里的Scaffold拆成一个单独的组件,这样子组件的context就能正确获取到MaterialApp提供的主题了。
修正后的完整代码:
import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( title: 'MyApp', theme: ThemeData( appBarTheme: const AppBarTheme(systemOverlayStyle: SystemUiOverlayStyle.dark), colorScheme: const ColorScheme( brightness: Brightness.light, primary: Colors.black, onPrimary: Colors.white, secondary: Colors.white, onSecondary: Colors.black, error: Colors.red, onError: Colors.white, background: Color(0xFFF5F5F5), onBackground: Colors.black, surface: Color(0xFFEEEEEE), onSurface: Colors.black, ), ), home: const HomeScreen(), ); } } class HomeScreen extends StatelessWidget { const HomeScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( body: const Center( child: Text("Welcome"), ), bottomNavigationBar: Container( padding: const EdgeInsets.all(8), color: Theme.of(context).colorScheme.primary, // 现在能正确获取自定义黑色主题 child: Row( children: [ IconButton( onPressed: () {}, icon: const Icon(Icons.search), ), ], ), ), ); } }
方法二:直接引用自定义主题对象
既然你已经手动定义了ThemeData,可以把它抽成成员变量,在需要使用颜色的地方直接引用,不需要通过Theme.of(context)。
修正后的完整代码:
import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); // 抽离自定义主题为成员变量 final ThemeData _customTheme = ThemeData( appBarTheme: const AppBarTheme(systemOverlayStyle: SystemUiOverlayStyle.dark), colorScheme: const ColorScheme( brightness: Brightness.light, primary: Colors.black, onPrimary: Colors.white, secondary: Colors.white, onSecondary: Colors.black, error: Colors.red, onError: Colors.white, background: Color(0xFFF5F5F5), onBackground: Colors.black, surface: Color(0xFFEEEEEE), onSurface: Colors.black, ), ); @override Widget build(BuildContext context) { return MaterialApp( title: 'MyApp', theme: _customTheme, home: Scaffold( body: const Center( child: Text("Welcome"), ), bottomNavigationBar: Container( padding: const EdgeInsets.all(8), color: _customTheme.colorScheme.primary, // 直接使用自定义主题的颜色 child: Row( children: [ IconButton( onPressed: () {}, icon: const Icon(Icons.search), ), ], ), ), ), ); } }
另外注意:你代码里class MyAppextends StatelessWidget存在拼写错误,应该是MyApp extends(类名和继承的类之间要有空格),这个笔误也需要修正。
内容的提问来源于stack exchange,提问作者divillysausages
相关产品推荐
相关产品推荐

