How to set a text background with Flutter?
TL;DR - (Updated 07-08-2019)
Using style property (backgroundColor
)
Text(
'Some text...',
style: TextStyle(backgroundColor: Colors.blue),
)
Using style property (background
)
Text(
'Some text...',
style: TextStyle(background: Paint()..color = Colors.blue),
)
Using a DecoratedBox
const DecoratedBox(
decoration: const BoxDecoration(color: Colors.blue),
child: const Text('Some text...'),
);
Long answer
First of all, welcome to Flutter and StackOverflow :)
That happens because are misunderstand the way you should develop with Flutter.
As opposed to what happens with other architectures where you start in the main()
function, instantiate your vars/objects and develop your flow from there, with Flutter you start your widget tree from your main()
function as well, usually with a MaterialApp
or CupertinoApp
and fit in all its children to create your app.
So, as an example to get what you want, you must add your Center
widget as the body of your Scaffold
and then give a TextStyle
to your Text
widget, providing the property color
. I gave it blue, but you can give it anything else you want. Thereby, this is your refactored code:
void main() => runApp(
MaterialApp(
home: Scaffold(
backgroundColor: const Color(0xFFD63031),
body: Center(
child: Text(
'MyText',
textDirection: TextDirection.ltr,
style: TextStyle(
background: Paint()..color = Colors.blue,
),
),
),
),
),
);
that will provide the following result
I suggest you take a look at the Awesome Flutter repo where you have a lot of good Flutter content to start with that can really help you out.
Simple you can set it in style
property..
Text(
'My Text...',
style: TextStyle(backgroundColor: Colors.grey),
)
You can set this many properties to text
in style: TextStyle()
{ bool inherit = true,
Color color,
Color backgroundColor,
double fontSize,
FontWeight fontWeight,
FontStyle fontStyle,
double letterSpacing,
double wordSpacing,
TextBaseline textBaseline,
double height,
Locale locale,
Paint foreground,
Paint background,
List<Shadow> shadows,
List<FontFeature> fontFeatures,
TextDecoration decoration,
Color decorationColor,
TextDecorationStyle decorationStyle,
double decorationThickness,
String debugLabel,
String fontFamily,
List<String> fontFamilyFallback,
String package
}