[![enter image description here][1]][1]
To paint in Flutter you use the [`CustomPaint`][2] widget. The `CustomPaint` widget takes a [`CustomPainter`][3] object as a parameter. In that class you have to override the `paint` method, which gives you a canvas that you can paint on. Here is the code to draw the text in the image above.
```dart
@override
void paint(Canvas canvas, Size size) {
final textStyle = TextStyle(
color: Colors.black,
fontSize: 30,
);
final textSpan = TextSpan(
text: 'Hello, world.',
style: textStyle,
);
final textPainter = TextPainter(
text: textSpan,
textDirection: TextDirection.ltr,
);
textPainter.layout(
minWidth: 0,
maxWidth: size.width,
);
final xCenter = (size.width - textPainter.width) / 2;
final yCenter = (size.height - textPainter.height) / 2;
final offset = Offset(xCenter, yCenter);
textPainter.paint(canvas, offset);
}
```
### Notes:
- If you are using a white background, be sure to set the text color to some other color besides white, which is the default.
- Flutter makes an effort to not assume a text direction, so you need to set it explicitly. The abbreviation `ltr` stands for left-to-right, which languages like English use. The other option is `rtl` (right-to-left), which languages like Arabic and Hebrew use. This helps to reduce bugs when the code is used in language contexts that developers were not thinking about.
### Context
Here is the **main.dart** code so that you can see it in context.
```dart
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: HomeWidget(),
),
);
}
}
class HomeWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(
child: CustomPaint( // <-- CustomPaint widget
size: Size(300, 300),
painter: MyPainter(),
),
);
}
}
class MyPainter extends CustomPainter { // <-- CustomPainter class
@override
void paint(Canvas canvas, Size size) {
// <-- Insert your painting code here.
}
@override
bool shouldRepaint(CustomPainter old) {
return false;
}
}
```
### See also
See [this article][4] for my fuller answer.
[1]:
[2]:
[To see links please register here]
[3]:
[To see links please register here]
[4]:
[To see links please register here]