Reputation: 53
I have a small Flutter application with Theme configured like this:
class MyApp extends StatelessWidget {
// This widget is the root of your application.
static final list = [
{
'name': 'test',
'password': 'foobar'
}
];
final store = Store(appStateReducers, initialState: AppState(list));
@override
Widget build(BuildContext context) {
return StoreProvider(
store: store,
child: MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.red,
appBarTheme: AppBarTheme(
color: Color.fromRGBO(250, 136, 54, 1)
),
textTheme: TextTheme(
body1: TextStyle(
color: Colors.red // text color is red for the whole applicatioin
)
)
),
initialRoute: '/',
routes: {
'/': (context) => NoAccountPageDart(),
'CreateAccount': (context) => CreateAccount(),
'Home': (context) => Home()
},
),
);
}
}
And on one of my screens I have a list of widgets where I want all text widgets to have another color. So I tried to use Theme widget folowing this guide for that like so:
//some code
child: Theme(
data: Theme.of(context).copyWith(
textTheme: Theme.of(context).textTheme.copyWith(
body1: TextStyle(color: Colors.white) // this is the color I want to use
)
),
child: Column(
children: <Widget>[
Text(accounts[index]['name']), // this is supposed to be white. But it's still red.
Text(accounts[index]['password'],
style: TextStyle(color: Colors.green))
],
),
));
//some code
But it didn't work. I have also tried to follow these answers on stackoverflow, and here how it looked in my code:
child: Theme(
data: Theme.of(context).copyWith(
textTheme: Theme.of(context).textTheme.apply(
bodyColor: Colors.white // this is the color I want to use
)
),
child: Column(
children: <Widget>[
Text(accounts[index]['name']), // this is supposed to be white. But it's still red.
Text(accounts[index]['password'],
style: TextStyle(color: Colors.green))
],
),
));
But this didn't work either. What am I doing wrong?
Upvotes: 5
Views: 5499
Reputation: 7148
Yes, you can use Theme widget as parent of your Scaffold in which you want to override global theme of app.
For Ex : Your Global theme is
theme: ThemeData( primarySwatch: Colors.blue, buttonColor: Colors.red ),
So, you have to use it with the syntax like,
color:Theme.of(context).buttonColor;
By, Adding Theme widget to specific screen like,
Theme(
data: ThemeData(
buttonColor: Colors.purple
),
child: Scaffold(
appBar: AppBar(
title: Text("Demo"),
),
body: Container(
child: RaisedButton(
onPressed:(){},
child:Text("Save"),
),
),
)
)
For this particular screen your button color gets directly applied from your nearest scaffold ThemeData to the RaisedButton Color. you don't need to reference it using Theme.of(context).
This way you can create a global ThemeData and apply it to all the screens which needs some different theme configurations other than declared in MaterialApp ThemeData.
I hope it helps.
Upvotes: 9