Home > OS >  Flutter: How to Auto-Fit Text Inside (Expanded) Floating Action Button?
Flutter: How to Auto-Fit Text Inside (Expanded) Floating Action Button?

Time:04-08

Let's say in Flutter you have:

return Row(
      children: [
        Expanded(
          child: FloatingActionButton(
            onPressed: () {},
            child: Text(myObject.unknownUntilRunTimeText),
          ),
        ),
        Expanded(
          child: FloatingActionButton(
            onPressed: () {},
            child: Text(myObject.unknownUntilRunTimeText),
          ),
        ),
      ],
    );

How do you make sure that text auto-fits (shrinks, presumably) to fit the button?

I tried to use FittedBox, but what it appears is happening in this case is that the FABS effective width is larger than the FAB (due to the expansion in a row, presumably)... and so even if you resize the text, it is still too large:

enter image description here

The vertical scribbles indicate where I assume Flutter is considering where the edges are.

CodePudding user response:

Use FittedBox. Example

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  static const String _title = 'Flutter Code Sample';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: _title,
      home: Scaffold(
        appBar: AppBar(title: const Text(_title)),
        body: Center(
          child: Container(),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed:(){},
          child: FittedBox(
            child: Text("Your text")
          ),
        ),
      ),
    );
  }
}

enter image description here enter image description here

CodePudding user response:

You can use FloatingActionButtom.extended()

  • Related