Trying to apply a text color to my header tiles in my list view. I define a headline text style with red text color (yes I have also tried this with Colors.red).
When I create the tile, I use the function _headerTile. Trying to load the style via Theme.of(context).textTheme.headline. However the text does not use ANY of the three properties I have defined in headline when I do this.
Is there something I'm doing wrong?
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'App',
home: Scaffold(
appBar: AppBar(
title: const Text(
'App',
)),
body: _buildList(context)),
theme: ThemeData(
textTheme: TextTheme(
headline: TextStyle(
color: Color.fromRGBO(255, 0, 0, 1),
fontSize: 72.0,
fontWeight: FontWeight.bold),
),
));
}
}
Widget _buildList(BuildContext context) => ListView(
children: [
_headerTile(context, "About Us")
],
);
ListTile _headerTile(BuildContext context, String title) => ListTile(
title: Text(title,
style: Theme.of(context)
.textTheme
.headline
contentPadding: EdgeInsets.symmetric(vertical: 0, horizontal: 8),
);
It's because you are calling Theme.of(context)
using the same context that is passed to MyApp
's build
function. This means that the ThemeData
returned by it will not be the one you have defined for the MaterialApp
.
When you get a widget's state by calling WidgetName.of(context)
, you basically use that context to look upwards through the widget hierarchy (all the parents of the widget to which that context belongs) until a widget state of that specific type is found. The context you are using belongs to the MyApp
widget, which is the parent of the MaterialApp
widget.
Try using routes
or onGenerateRoute
instead of home
- this will give you a context to build your routes that sits below the MaterialApp
widget, so that when you call Theme.of(context)
it will return the expected ThemeData
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With