flutter 局部主题
如果我们想在应用程序的一部分中覆盖应用程序的全局的主题,我们可以将要覆盖得部分封装在一个Theme
Widget中。
有两种方法可以解决这个问题:创建特有的ThemeData
或扩展父主题。
1.创建特有的ThemeData
如果我们不想继承任何应用程序的颜色或字体样式,我们可以通过new ThemeData()
创建一个实例并将其传递给Theme
Widget。
new Theme( // Create a unique theme with "new ThemeData" data: new ThemeData( accentColor: Colors.yellow, ), child: new FloatingActionButton( onPressed: () {}, child: new Icon(Icons.add), ), );
2.扩展父主题
扩展父主题时无需覆盖所有的主题属性,我们可以通过使用copyWith
方法来实现。
new Theme( // Find and Extend the parent theme using "copyWith". Please see the next // section for more info on `Theme.of`. data: Theme.of(context).copyWith(accentColor: Colors.yellow), child: new FloatingActionButton( onPressed: null, child: new Icon(Icons.add), ), );
具体代入例子:
import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; void main() { runApp(new MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { final appName = 'Custom Themes'; return new MaterialApp( title: appName, theme: new ThemeData( brightness: Brightness.dark, primaryColor: Colors.lightBlue[800], accentColor: Colors.cyan[600], ), home: new MyHomePage( title: appName, ), ); } } class MyHomePage extends StatelessWidget { final String title; MyHomePage({Key key, @required this.title}) : super(key: key); @override Widget build(BuildContext context) { return new Scaffold( appBar: new AppBar( title: new Text(title), ), body: new Center( child: new Container( color: Theme.of(context).accentColor, child: new Text( 'Text with a background color', style: Theme.of(context).textTheme.title, ), ), ), floatingActionButton: new Theme( data: Theme.of(context).copyWith(accentColor: Colors.yellow), child: new FloatingActionButton( onPressed: null, child: new Icon(Icons.add), ), ), ); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
2018-12-05 iOS tableview cell点击无反应 (无高亮选中),出现一条白线怎么办?
2016-12-05 Storyboard中segue(转场)使用