Reputation: 639
I've been trying to override my app theme for hours now without success, and I'd be very grateful for any help I can get.
I think I'm doing exactly what this questioner is doing, but for me the theme is not overridden for some reason and I can't understand why. No matter what I do the text 'hey' is not white. Any ideas why? Thank you.
@override
Widget build(BuildContext context) {
final ThemeData _themeData = Theme.of(context);
return Theme(
data: _themeData.copyWith(
textTheme: _themeData.textTheme.copyWith(
headline: _themeData.textTheme.headline.copyWith(
color: Colors.white,
),
),
),
child: Center(
child: Text(
'hey',
style: Theme.of(context).textTheme.headline,
),
),
);
}
Upvotes: 4
Views: 3191
Reputation: 639
I realized the reason why it didn't work is because the theme needs to be overridden before the build method! Then the context will be of the new theme.
Upvotes: 4
Reputation: 51316
Text style
is updated using - DefaultTextStyle
. Text
does not use Theme.
Text uses DefaultTextStyle
, which is edited by MaterialApp (or some other widgets such as AppBar) with values from the Theme.
Working Code:
body: Center(
child: DefaultTextStyle(
style: TextStyle().copyWith(
color: Colors.red,
),
child: Text(
'hey', // red color
// style: Theme.of(context).textTheme.headline,
),
),
),
Update: at MaterialApp
theme level.
class MyHome extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
textTheme: TextTheme(headline: TextStyle(color: Colors.redAccent))),
home: MyApp());
}
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
final ThemeData _themeData = Theme.of(context);
return Scaffold(
body: Center(
child: Center(
child: Text(
'hey', // red color
style: _themeData.textTheme.headline,
),
),
),
);
}
}
To update on the fly:
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
final ThemeData _themeData = Theme.of(context);
return Scaffold(
body: Center(
child: Center(
child: Text(
'hey', //Green color
style: _themeData.textTheme.headline.apply(color: Colors.green),
),
),
),
);
}
}
Upvotes: 1