Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter app, Theme.of(context) style doesn't work on text

Tags:

flutter

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),
    );
like image 981
zafrani Avatar asked Mar 04 '23 12:03

zafrani


1 Answers

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.

like image 189
Ovidiu Avatar answered Mar 15 '23 20:03

Ovidiu