I am trying to make a custom theme that is applied to only the children of that theme.
However when I run the app, the Text widget that displays "hello" is still blue. I want to make it yellow.
Can anyone show me where i'm going wrong?
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
brightness: Brightness.dark,
primaryColor: Colors.lightBlue[800],
accentColor: Colors.cyan[600],
textTheme: TextTheme(body1: TextStyle(color: Colors.blue))),
home: new MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: Text(widget.title),
),
body: Center(
child: Theme(
data: Theme.of(context).copyWith(
textTheme:
TextTheme(body1: TextStyle(color: Colors.yellow))),
child: Text("hello"))));
}
}
To theme a Text
you need to assign the value to style
property
Text("Hello", style: Theme.of(context).textTheme.body1)
Make sure to use the correct context
when doing Theme.of(context)
. You need a context
that is a child of your new Theme
.
You'll need to do the following :
Theme(
child: Builder(
builder: (context) {
return Text("Hello", style: Theme.of(context).textTheme.body1);
}
)
)
This is another way, because sometimes it's more convenient to override the default style
Text widget:
If the
style
argument is null, the text will use the style from the closest enclosingDefaultTextStyle
.
@override
Widget build(BuildContext context) {
final DefaultTextStyle defaultTextStyle = DefaultTextStyle.of(context);
TextStyle effectiveTextStyle = style;
if (style == null || style.inherit)
effectiveTextStyle = defaultTextStyle.style.merge(style);
So, if you want to override the default style for the Text
widget (when you do not pass the style
property), you need to use the DefaultTextStyle
widget
return new Scaffold(
appBar: new AppBar(
title: Text(widget.title),
),
body: Center(
child: DefaultTextStyle(
style: Theme.of(context).textTheme.body1.copyWith(color: Colors.yellow),
child: Text("hello"))
)
);
MaterialApp
uses its TextStyle
as its DefaultTextStyle
to encourage developers to be intentional about their DefaultTextStyle
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