Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String length in pixels flutter

I have a String ('hello') and a font size (20), is there any method that can give me the length of the string in pixels?

final String foo = 'hello';
final double fontSize = 20.0:
final pix = pixelsOf(foo, fontSize); //something like this
like image 273
m.delloso Avatar asked Nov 01 '25 15:11

m.delloso


1 Answers

here is sample code:

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(home: Scaffold(body: Home())));
}

class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var text = 'I\'m awesome!';
    var size = calcTextSize(text, TextStyle(fontSize: 20));

    return Center(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Text(text, style: TextStyle(fontSize: 20)),
          Container(width: size.width, height: 4, color: Colors.blue),
          Text(size.width.toString()), // this blue line has exactly same width as text above
        ],
      ),
    );
  }

  Size calcTextSize(String text, TextStyle style) {
    final TextPainter textPainter = TextPainter(
      text: TextSpan(text: text, style: style),
      textDirection: TextDirection.ltr,
      textScaleFactor: WidgetsBinding.instance.window.textScaleFactor,
    )..layout();
    return textPainter.size;
  }
}

enter image description here


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!