Skip to content

Instantly share code, notes, and snippets.

@yjbanov
Created June 26, 2024 00:10
Show Gist options
  • Save yjbanov/6611afca7a45eb9d038a4867598ee33c to your computer and use it in GitHub Desktop.
Save yjbanov/6611afca7a45eb9d038a4867598ee33c to your computer and use it in GitHub Desktop.
An example of a paragraph of text
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Paragraph Example',
debugShowCheckedModeBanner: false,
theme: ThemeData(
colorSchemeSeed: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
title: Text('Flutter Paragraph Example'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
width: 200,
height: 400,
child: CustomPaint(
painter: ParagraphPainter(),
),
),
],
),
),
),
);
}
}
class ParagraphPainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
// Custom painter is used to demonstrate the lowest-level public API
// available to Flutter developers, but typically this API is wrapped
// into something more convenient with better syntax and support for
// UI features expected by users, such as accessibility and text
// selection.
final builder = ui.ParagraphBuilder(ui.ParagraphStyle());
builder.addText(
'This is a paragraph of text rendered by Flutter. Text can have different ');
builder.pushStyle(ui.TextStyle(
fontSize: 36,
fontStyle: ui.FontStyle.italic,
));
{
builder.addText('styles');
}
builder.pop();
builder.addText(' and ');
builder.pushStyle(ui.TextStyle(decoration: ui.TextDecoration.underline));
{
builder.addText('decorations');
}
builder.pop();
builder.addText('. A span may be ');
builder.pushStyle(ui.TextStyle(
fontSize: 24,
fontWeight: ui.FontWeight.bold,
background: ui.Paint()..color = Color.fromARGB(150, 0, 255, 0),
foreground: ui.Paint()
..color = Color.fromARGB(255, 0, 0, 255)
..blendMode = ui.BlendMode.multiply,
));
{
builder.addText('blended');
}
builder.pop();
builder.addText(' differently. It may also have a\n');
final gradient = LinearGradient(colors: [
Colors.deepPurple,
Colors.deepOrange,
]);
builder.pushStyle(ui.TextStyle(
fontSize: 36,
fontWeight: ui.FontWeight.bold,
letterSpacing: 15,
foreground: ui.Paint()
..shader = gradient.createShader(
Rect.fromLTWH(0, 0, 200, 24),
),
));
{
builder.addText('shader');
}
builder.pop();
builder.addText('\napplied to it.');
final paragraph = builder.build();
paragraph.layout(ui.ParagraphConstraints(width: size.width));
canvas.drawParagraph(paragraph, ui.Offset.zero);
}
@override
bool shouldRepaint(ParagraphPainter oldDelegate) => true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment