How to make text as big as the width allows in flutter

谁说胖子不能爱 提交于 2019-12-12 10:38:35

问题


I have a Container where I need to show a barcode (it's a app for virtual fidelity cards) and I'd love to have the barcode to be as wide as possible on the screen. For now I set the font size at a reasonable size that suits all devices, but it's only temporary of course. How can I solve this? This is the code I am using for building the Widget.

@override
Widget build(BuildContext context) {
  return Scaffold(
      appBar: AppBar(
      title: Text(_title),
    ),
    body: Container(
    padding: const EdgeInsets.all(12.0),
    child: Column(
      children: <Widget>[ 
        SizedBox(
          width: double.infinity,
          child: Text(_barcode, style: TextStyle(fontFamily: 'Code128', fontSize: 90.0))
        ),
        Text(_barcode, style: TextStyle(fontSize: 40.0))
        ]
      ),
    )
  );
}

回答1:


I believe what you're looking for is FittedBox.

BoxFit applies whichever 'fit' you want to stretch/scale the child to fit in the box. It doesn't perform a pure 'stretch' on the text but rather the space it should take up. You shouldn't specify the text's size at the same time.

That looks like this:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  MyAppState createState() {
    return new MyAppState();
  }
}

class MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: SafeArea(
          child: Center(
            child: Container(
              color: Colors.blue,
              width: 300.0,
              height: 200.0,
              child: FittedBox(
                fit: BoxFit.contain,
                child: Text("Whee"),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

If you're wanting to actually 'stretch' the text (i.e. make the actual characters wider or taller) you'll have to do something a bit more custom.

If that's the case, look at CustomPaint, CustomPainter, TextPainter, and the Canvas translate & scale options. Basically, you would need to create a class extending CustomPainter in which you created a TextPainter, laid it out at a particular size, painted it onto the canvas, and then scaled it to fit the actual size of the CustomPainter (or do you scale the canvas first - I forget...). Then you'd pass an instance of that class to CustomPaint.




回答2:


you can use fitted box widget.

FittedBox(child:Text('text sample'));

https://api.flutter.dev/flutter/widgets/FittedBox-class.html




回答3:


Use TextPainter.width and a for loop to find the largest fitting font size (adding +1 is not very efficient, you may want to fine-tune that):

import 'package:flutter/material.dart';

main() => runApp(MaterialApp(
      home: MyHomePage(),
      theme: ThemeData(platform: TargetPlatform.iOS),
    ));

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Text autoscale'),
      ),
      body: Padding(
        padding: EdgeInsets.all(32.0),
        child: Center(
          child: LayoutBuilder(
            builder: (BuildContext context, BoxConstraints constraints) {
              final text = 'Hello World';
              final style = TextStyle(fontWeight: FontWeight.bold); // apply your barcode font here
              final fontSize = calculateAutoscaleFontSize(text, style, 30.0, constraints.maxWidth);
              return Text(
                text,
                style: style.copyWith(fontSize: fontSize),
                maxLines: 1,
              );
            },
          ),
        ),
      ),
    );
  }
}

double calculateAutoscaleFontSize(String text, TextStyle style, double startFontSize, double maxWidth) {
  final textPainter = TextPainter(textDirection: TextDirection.ltr);

  var currentFontSize = startFontSize;

  for (var i = 0; i < 100; i++) {
    // limit max iterations to 100
    final nextFontSize = currentFontSize + 1;
    final nextTextStyle = style.copyWith(fontSize: nextFontSize);
    textPainter.text = TextSpan(text: text, style: nextTextStyle);
    textPainter.layout();
    if (textPainter.width >= maxWidth) {
      break;
    } else {
      currentFontSize = nextFontSize;
      // continue iteration
    }
  }

  return currentFontSize;
}



回答4:


Wrap the text within a FittedBox widget, to force the text to be enclosed by a box. The FittedBox's size will depend on it's parent's widget. Within the FittedBox, the Text widget, can simply 'cover' the box, so the text doesn't stretch to fill the available space within the FittedBox. The enum BoxFit.fill, is a way to stretch the text to fit the entire space available within the FittedBox. You can change the dimensions of the box by altering the height and width of the FittedBox's parent, the Container.

Container(
  height: _height,
  width: _width,
  FittedBox(               
    fit: BoxFit.fill,
    child: Text("Whee"),
  )
)


来源:https://stackoverflow.com/questions/51674962/how-to-make-text-as-big-as-the-width-allows-in-flutter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!