如何覆盖应用程序的一部分的主题?



我有一个小型的 Flutter 应用程序,其主题配置如下:

class MyApp extends StatelessWidget {
// This widget is the root of your application.
static final list = [
{
'name': 'test',
'password': 'foobar'
}
];
final store = Store(appStateReducers, initialState: AppState(list));
@override
Widget build(BuildContext context) {
return StoreProvider(
store: store,
child: MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.red,
appBarTheme: AppBarTheme(
color: Color.fromRGBO(250, 136, 54, 1)
),
textTheme: TextTheme(
body1: TextStyle(
color: Colors.red // text color is red for the whole applicatioin
)
)
),
initialRoute: '/',
routes: {
'/': (context) => NoAccountPageDart(),
'CreateAccount': (context) => CreateAccount(),
'Home': (context) => Home()
},
),
);
}
}

在我的一个屏幕上,我有一个小部件列表,我希望所有文本小部件都有另一种颜色。所以我尝试使用本指南的主题小部件,如下所示:

//some code
child: Theme(
data: Theme.of(context).copyWith(
textTheme: Theme.of(context).textTheme.copyWith(
body1: TextStyle(color: Colors.white) // this is the color I want to use
)
),
child: Column(
children: <Widget>[
Text(accounts[index]['name']), // this is supposed to be white. But it's still red.
Text(accounts[index]['password'],
style: TextStyle(color: Colors.green))
],
),
));
//some code

但它没有用。我也尝试在stackoverflow上遵循这些答案,以及它在我的代码中的样子:

child: Theme(
data: Theme.of(context).copyWith(
textTheme: Theme.of(context).textTheme.apply(
bodyColor: Colors.white // this is the color I want to use
)
),
child: Column(
children: <Widget>[
Text(accounts[index]['name']), // this is supposed to be white. But it's still red.
Text(accounts[index]['password'],
style: TextStyle(color: Colors.green))
],
),
));

但这也没有用。我做错了什么?

是的,您可以使用主题小部件作为要覆盖应用程序的全局主题的脚手架的父级

例如:您的全球主题是

主题:主题数据( 原色色板:颜色.蓝色, 按钮颜色: 颜色.红色 ),

因此,您必须将其与语法一起使用,例如,

color:Theme.of(context).buttonColor;

通过,将主题小部件添加到特定屏幕,例如,

Theme(
data: ThemeData(
buttonColor: Colors.purple
),
child: Scaffold(
appBar: AppBar(
title: Text("Demo"),
),
body: Container(
child: RaisedButton(
onPressed:(){},
child:Text("Save"),
),        
),
)
)

对于此特定屏幕,您的按钮颜色直接从最近的脚手架主题数据应用于凸起按钮颜色。 你不需要使用 Theme.of(context( 引用它。

通过这种方式,您可以创建一个全局主题数据并将其应用于需要一些不同主题配置的所有屏幕,而不是在 MaterialApp 主题数据中声明。

我希望它有所帮助。

相关内容

最新更新