Skip to content

Instantly share code, notes, and snippets.

@DaisukeNagata
Created April 9, 2022 13:05
Show Gist options
  • Save DaisukeNagata/382b3766d5094119a86d9cc3ee832518 to your computer and use it in GitHub Desktop.
Save DaisukeNagata/382b3766d5094119a86d9cc3ee832518 to your computer and use it in GitHub Desktop.
How to get the size of text
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Size sizeCheck = Size.zero;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
alignment: Alignment.center,
width: MediaQuery.of(context).size.width,
child: Text('$sizeCheck'),
)
],
),
floatingActionButton: TextButton(
child: const Text("Button"),
onPressed: () {
setState(() {
TextSpan textSpan = const TextSpan(children: <TextSpan>[
TextSpan(
text: "123\n456\n789",
)
]);
TextPainter textPainter = TextPainter(
text: textSpan,
textDirection: TextDirection.ltr,
);
textPainter.layout(
minWidth: 0,
maxWidth: MediaQuery.of(context).size.width,
);
sizeCheck = textPainter.size;
});
},
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment