I don't understand the point of the Theme class in Flutter

Viewed 699

So I was working with Flutter and I needed a custom Widget for a ListView where every widget has its own theme based on some data.

The proper way to do it seems to be something like this:

class CustomWidget extends StatefulWidget {
  CustomWidget({Key key, this.data}) : super(key: key);

  final Color data;
  @override
  _CustomWidgetState createState() => _CustomWidgetState();
}

class _CustomWidgetState extends State<CustomWidget> {
  @override
  Widget build(BuildContext context) {
    return Theme(
      data: ThemeData(primaryColor: widget.data),
      child: Builder(builder: (context) {
        return Container(
          color: Theme.of(context).primaryColor,
        );
      }),
    );
  }
}

But if I do it like this, what exactly is the advantage of this?
Specifically applying the color in the container? Why can't I just do color: widget.data?

Wouldn't it make more sense if things like TextTheme automatically applied to every Text() decadence of Theme()?

1 Answers

The ThemeData is used to configure a Theme or MaterialApp widget:

https://api.flutter.dev/flutter/material/ThemeData-class.html

The primaryColor value does not affect the color of the Text widget, from the docs:

The background color for major parts of the app (toolbars, tab bars, etc)

If you want to change the color of the text then you can use the textTheme property:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        accentColor : Colors.black,
        textTheme: TextTheme(bodyText2: TextStyle(color: Colors.purple)),
        primaryColor : Colors.black
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

primaryColor: is used for the appbar

accentColor: is used to color the foreground

textTheme: will change the color of the text and style it

working example:

https://dartpad.dartlang.org/bba537def9dbfa771400309a4e6415ed

Related