Flutter应用主题主色获取问题求助
Flutter应用主题主色获取问题求助
嘿,我看你在给Flutter应用配置主题时,遇到了无法获取主色的问题,我来帮你捋捋~
先把你没写完的代码补全一下,方便咱们分析:
import 'package:flutter/material.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( colorScheme: const ColorScheme.light( primary: Colors.blue, secondary: Colors.amber, ), useMaterial3: true, ), darkTheme: ThemeData( colorScheme: const ColorScheme.dark( primary: Colors.grey, secondary: Colors.white, ), useMaterial3: true, ), themeMode: ThemeMode.system, home: Scaffold( body: Center( child: SizedBox( height: 200, width: 200, child: Container( // 你应该是想在这里使用主题的primary颜色,但直接Theme.of(context)会有问题 color: Theme.of(context).colorScheme.primary, ), ), ), ), ); } }
问题原因
你现在的写法里,Theme.of(context)是在MaterialApp的同一个build方法里调用的,这时候的context还没有关联到当前配置的ThemeData——毕竟MaterialApp本身才是提供主题上下文的组件,所以自然拿不到正确的主色。
解决方法
这里有几种简单的解决方式,你可以选适合自己的:
方法1:把Home内容抽成独立的Widget
把Scaffold部分放到一个新的Widget里,这样新Widget的context就能获取到MaterialApp提供的主题了:
import 'package:flutter/material.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( colorScheme: const ColorScheme.light( primary: Colors.blue, secondary: Colors.amber, ), useMaterial3: true, ), darkTheme: ThemeData( colorScheme: const ColorScheme.dark( primary: Colors.grey, secondary: Colors.white, ), useMaterial3: true, ), themeMode: ThemeMode.system, home: const HomePage(), // 换成独立的Widget ); } } class HomePage extends StatelessWidget { const HomePage({super.key}); @override Widget build(BuildContext context) { return Scaffold( body: Center( child: SizedBox( height: 200, width: 200, child: Container( color: Theme.of(context).colorScheme.primary, // 这里就能正确获取主色了 ), ), ), ); } }
方法2:使用Builder组件包裹
如果不想新建Widget,也可以用Builder来提供一个能访问主题的上下文:
home: Builder( builder: (context) { return Scaffold( body: Center( child: SizedBox( height: 200, width: 200, child: Container( color: Theme.of(context).colorScheme.primary, ), ), ), ); }, )
方法3:直接在ThemeData里引用(如果是配置主题内的颜色)
要是你是在配置主题的其他属性时想用主色,也可以直接在ThemeData里通过colorScheme来引用,比如:
theme: ThemeData( colorScheme: const ColorScheme.light( primary: Colors.blue, secondary: Colors.amber, ), useMaterial3: true, elevatedButtonTheme: ElevatedButtonThemeData( style: ElevatedButton.styleFrom( backgroundColor: colorScheme.primary, // 直接用当前colorScheme的primary ), ), ),
这样调整后,你就能正确获取到主题里的主色啦~
备注:内容来源于stack exchange,提问作者pasanmaduranga
相关产品推荐
相关产品推荐

