Common textStyle for all the Text widgets inside a widget in flutter
Let's start with the problem we want to solve here,
Problem Statement: It’s a very common case that in a column there is a list of Text widgets is there, and we want to give a common text style to all the Text widgets in the Column, for example in the DrawerHeader widget we want a similar situation. The design is given below,
And the code for the above will be,
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.light().copyWith(),
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center(
child: Text(
'Hello, World!',
style: Theme.of(context).textTheme.headline4,
),
),
appBar: AppBar(),
drawer: Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: [
DrawerHeader(
decoration: BoxDecoration(
color: Colors.blue.shade800,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('User Name', textScaleFactor: 1.5),
SizedBox(height: 8),
Text('user_email@gmail.com'),
SizedBox(height: 4),
Text('+91 98765 43210'),
SizedBox(height: 4),
Text('Expiry: 28 Apr 2024'),
],
),
)
],
),
),
),
);
}
}
The above code will generate an output with all the texts in BLACK color,
the output of the above code is,
But if we want to give a common style to all the Text widgets then we can use the widget called “DefaultTextStyle” and supply a default style to it.
The ideal code is given below,
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.light().copyWith(),
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center(
child: Text(
'Hello, World!',
style: Theme.of(context).textTheme.headline4,
),
),
appBar: AppBar(),
drawer: Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: [
DrawerHeader(
decoration: BoxDecoration(
color: Colors.blue.shade800,
),
child: DefaultTextStyle(
style: TextStyle(color: Colors.white),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('User Name', textScaleFactor: 1.5),
SizedBox(height: 8),
Text('user_email@gmail.com'),
SizedBox(height: 4),
Text('+91 98765 43210'),
SizedBox(height: 4),
Text('Expiry: 28 Apr 2024'),
],
),
),
)
],
),
),
),
);
}
}
You can run the above code:
That is it,
DefaultTextStyle(
style: TextStyle(color: Colors.white),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('User Name', textScaleFactor: 1.5),
SizedBox(height: 8),
Text('user_email@gmail.com'),
SizedBox(height: 4),
Text('+91 98765 43210'),
SizedBox(height: 4),
Text('Expiry: 28 Apr 2024'),
],
),
),
In the above code, the DefaultTextStyle widget supplies a common style to all the Text widgets child to it.
The output will be as below,
You can run the above code: