2

i want to resize the text of a TextField() widget in order to fit the max width of its Expanded() parent, this width is determined by flex: 10 as you can see in the code.

However, i do not know how can i achieve this result. I also tried the AutoSizeTextField() package with no success. Maybe someone can figure out how to do this.

Thank you in advance.

Edit. If it is not clear, the text is entered by the user. I want to resize it dynamically. The following image is just an example of the current behaviour of the App when user enters "This text should be resized".

enter image description here

Edit. I updated the code so that is clear what i am trying to do.

I have a list of transactions. When the user click on a transaction a dialog will popup in order to let the user edit the info he has provided.

This is the code which call the dialog, the dialog is ModificaTransazione().

Material(
            color: Colors.white,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(10.0),
            ),
            child: InkWell(
              borderRadius: BorderRadius.circular(10),
              onTap: () {
                //sleep(Duration(milliseconds: 800));
                showDialog(
                  context: context,
                  builder: (context) {
                    return Dialog(
                      insetPadding: EdgeInsets.only(
                          bottom: 0.0), //QUESTO TOGLIE SPAZIO DALLA TASTIERA
                      shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(40)),
                      elevation: 16,
                      child: ModificaTransazione(
                          idtransazione: tx.id,
                          titolotransazione: tx.titolo,
                          importotransazione: tx.costo,
                          datatransazione: tx.data,
                          indicetransazione: tx.indicecategoria,
                          notatransazione: tx.nota,
                          listatransazioni: widget.transactions,
                          eliminatransazione: widget.deleteTx,
                          listanomicategorie: widget.listanomicategorie,
                          refreshSezioneFinanziaria:
                              widget.refreshFinanceScreen,
                          size: size),
                    );
                  },
                ).then((_) {
                  setState(() {});
                });
              },
              child: Container(
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(10),
                ),
                child: SizedBox(
                  height: size.height * 0.10,
                  // color: Colors.red,
                  child: Row(
                    children: [
                      Expanded(
                        flex: 4,
                        child: Container(
                          margin: const EdgeInsets.only(left: 15),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              FittedBox(
                                child: Text(
                                  tx.titolo,
                                  style: const TextStyle(
                                    fontSize: 16,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                              ),
                              FittedBox(
                                child: Text(
                                  DateFormat('dd MMMM, yyyy', 'it')
                                      .format(tx.data),
                                  style: const TextStyle(
                                    color: Colors.grey,
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                      Expanded(
                        flex: 5,
                        child: Container(
                          alignment: Alignment.centerRight,
                          margin: const EdgeInsets.symmetric(horizontal: 15),
                          child: FittedBox(
                            child: Text(
                              '- ${ciframostrata(tx.costo)} €',
                              style: const TextStyle(
                                  fontWeight: FontWeight.bold,
                                  fontSize: 20,
                                  color: Color(0xFF7465fc)),
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ),

This is "ModificaTransazione()" literally "Edit Transaction" in Italian.

        import 'package:auto_size_text/auto_size_text.dart';
        import 'package:flutter/material.dart';
        import 'package:flutter_application_1/models/transaction.dart';
        import 'package:flutter_application_1/widget/transactions_list.dart';
        import 'package:intl/intl.dart';
        import 'package:auto_size_text_field/auto_size_text_field.dart';
        
        class ModificaTransazione extends StatefulWidget {
          ModificaTransazione({
            Key? key,
            required this.size,
            required this.idtransazione,
            required this.titolotransazione,
            required this.importotransazione,
            required this.datatransazione,
            required this.indicetransazione,
            required this.notatransazione,
            required this.listatransazioni,
            required this.eliminatransazione,
            required this.listanomicategorie,
            required this.refreshSezioneFinanziaria,
          }) : super(key: key);
        
          final Size size;
          final String idtransazione;
          String titolotransazione;
          double importotransazione;
          DateTime datatransazione;
          int indicetransazione;
          String notatransazione;
          List<String> listanomicategorie;
          List<Transaction> listatransazioni;
          final Function eliminatransazione;
          final Function refreshSezioneFinanziaria;
        
          @override
          State<ModificaTransazione> createState() => _ModificaTransazioneState();
        }
        
        class _ModificaTransazioneState extends State<ModificaTransazione> {
          var _notaController = TextEditingController();
          var _importoController = TextEditingController();
          var _titoloController = TextEditingController();
        
          @override
          void initState() {
            super.initState();
            if (widget.notatransazione != "") {
              _notaController = TextEditingController(text: widget.notatransazione);
            } else {
              _notaController = TextEditingController(text: "Aggiungi");
            }
        
            _importoController = TextEditingController(
                text: "${ciframostrata(widget.importotransazione)}");
            _titoloController = TextEditingController(text: widget.titolotransazione);
          }
        
          @override
          Widget build(BuildContext context) {
            
            return SingleChildScrollView(
              child: Container(
                width: widget.size.width * 0.8,
                height: widget.size.height * 0.60,
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(10),
                ),
                child: Padding(
                  padding:
                      const EdgeInsets.only(top: 30, left: 30, right: 30, bottom: 30),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Row(
                        children: [
                          GestureDetector(
                            onTap: () {
                              setState(() {
                                Navigator.of(context).pop();
                              });
                            },
                            child: Icon(
                              Icons.cancel,
                              color: Colors.black,
                            ),
                          ),
                          Spacer(),
                          Expanded(
//
// THIS IS WHAT I WANT TO RESIZE, BUT FITTEDBOX IS CAUSING RENDERBOX IS NOT LAID OUT
//
                            flex: 10,
                            child: FittedBox(
                              fit: BoxFit.fitWidth,
                              child: TextField(
                                maxLines: 1,
                                decoration: InputDecoration(
                                  border: InputBorder.none,
                                ),
                                controller: _titoloController,
                                textAlign: TextAlign.center,
                                style: TextStyle(
                                  fontSize: 20,
                                  fontWeight: FontWeight.bold,
                                ),
                                onSubmitted: (_) => salvaModifica(),
                              ),
                            ),
                          ),
                          Spacer(),
                          GestureDetector(
                              child: Icon(
                                Icons.delete_outline_rounded,
                                color: Colors.black,
                              ),
                              onTap: () {
                                print("Transazione Eliminata");
        
                                widget.eliminatransazione(widget.idtransazione);
                                Navigator.of(context).pop();
                              }),
                        ],
                      ),
                      Container(
                        padding: EdgeInsets.all(15),
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(15),
                          color: Theme.of(context).primaryColor.withOpacity(0.1),
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Flexible(
                              flex: 4,
                              child: TextField(
                                decoration: InputDecoration(
                                  border: InputBorder.none,
                                ),
                                controller: _importoController,
                                keyboardType: const TextInputType.numberWithOptions(
                                    decimal: true),
                                textAlign: TextAlign.center,
                                style: TextStyle(
                                  fontSize: 60,
                                  color: Theme.of(context).primaryColor,
                                ),
                                onSubmitted: (_) => salvaModifica(),
                              ),
                            ),
                            Flexible(
                              //color: Colors.red,
                              //alignment: Alignment.centerRight,
                              //width: widget.size.width * 0.10,
                              // color: Colors.red,
                              child: Text(
                                "€",
                                style: TextStyle(
                                  fontSize: 40,
                                  color:
                                      Theme.of(context).primaryColor.withOpacity(0.8),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
        
                      //   AutoSizeText(
                      //     "${ciframostrata(widget.importotransazione)} €",
                      //     maxLines: 1,
                      //     style: TextStyle(
                      //       fontSize: 70,
                      //       color: Theme.of(context).primaryColor,
                      //     ),
                      //   ),
                      // ),
        
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            "Categoria",
                            style: TextStyle(
                              fontWeight: FontWeight.bold,
                              fontSize: 15,
                              color: Colors.grey,
                            ),
                          ),
                          Container(
                            child: Row(
                              children: [
                                GestureDetector(
                                  child: Text(
                                    "${funzioneCategoria(indicenuovo ?? widget.indicetransazione, widget.listanomicategorie)[2]} ",
                                    style: TextStyle(
                                        fontWeight: FontWeight.bold,
                                        fontSize: 15,
                                        color: funzioneCategoria(
                                            indicenuovo ?? widget.indicetransazione,
                                            widget.listanomicategorie)[1]),
                                  ),
                                  onTap: _askedToLead,
                                ),
                                Icon(
                                    funzioneCategoria(
                                        indicenuovo ?? widget.indicetransazione,
                                        widget.listanomicategorie)[0],
                                    color: funzioneCategoria(
                                        indicenuovo ?? widget.indicetransazione,
                                        widget.listanomicategorie)[1]),
                              ],
                            ),
                          ),
                        ],
                      ),
        
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            "Data",
                            style: TextStyle(
                              fontWeight: FontWeight.bold,
                              fontSize: 15,
                              color: Colors.grey,
                            ),
                          ),
                          InkWell(
                            // borderRadius: BorderRadius.circular(10),
                            onTap: _presentDatePicker,
        
                            child: Text(
                              DateFormat('dd MMMM, yyyy', 'it')
                                  .format(_selectedDate ?? widget.datatransazione),
                              style: TextStyle(
                                color: Colors.black, //Theme.of(context).primaryColor,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ),
                        ],
                      ),
        
                      Container(
                        //color: Colors.red,
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Expanded(
                              child: Text(
                                "Nota",
                                style: TextStyle(
                                  fontWeight: FontWeight.bold,
                                  fontSize: 15,
                                  color: Colors.grey,
                                ),
                              ),
                            ),
                            Expanded(
                                child: (_notaController.text != "Aggiungi")
                                    ? TextField(
                                        textAlign: TextAlign.end,
                                        decoration: InputDecoration(
                                          border: InputBorder.none,
                                        ),
                                        controller: _notaController,
                                        style: TextStyle(
                                          fontWeight: FontWeight.bold,
                                          color: Colors.black,
                                        ),
                                        onSubmitted: (_) => salvaModifica(),
                                      )
                                    : TextField(
                                        textAlign: TextAlign.end,
                                        decoration: InputDecoration(
                                          border: InputBorder.none,
                                        ),
                                        controller: _notaController,
                                        style: TextStyle(
                                          fontWeight: FontWeight.bold,
                                          color: Colors.grey[600],
                                        ),
                                        onSubmitted: (_) => salvaModifica(),
                                      )),
                          ],
                        ),
                      ),
        
                      modificato == true
                          ? TextButton(
                              child: Text("Salva"),
                              style: ButtonStyle(
                                backgroundColor: MaterialStateProperty.all(
                                    Theme.of(context).primaryColor),
                                foregroundColor:
                                    MaterialStateProperty.all(Colors.white),
                              ),
                              onPressed: () {
                                premuto = true;
                                salvaModifica();
                              },
                            )
                          : SizedBox(),
                    ],
                  ),
                ),
              ),
            );
          }
iocomxda
  • 73
  • 8
  • As you can see in your second illustration the text is much smaller, So reduce your fonsize – Davis Nov 24 '21 at 23:54
  • This is a Textfield(), so the text changes as the user enters it. The lenght of the text is variable. I want the text to be resized dynamically while the user enters it. @Davis – iocomxda Nov 24 '21 at 23:56

2 Answers2

0

You can use the FittedBox widget to dynamically change text size based on width or height.

      FittedBox(
            fit: BoxFit.fitWidth,
            child: TextField(
                maxLines: 1,
                decoration: InputDecoration(
                  border: InputBorder.none,
                ),
                controller: _titoloController,
                textAlign: TextAlign.center,
                style: TextStyle(
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                ),
                onSubmitted: (_) => salvaModifica(),
              )),

The text will be resized based on the width of Expanded.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Rohith Nambiar
  • 2,957
  • 4
  • 17
  • 37
  • This is not working since it is causing `RenderBox was not laid out.` I added more code so that it is clear what i am doing. Could you check it out? – iocomxda Nov 25 '21 at 10:25
  • I will try, but you can also refer from here: https://stackoverflow.com/questions/50751226/how-to-dynamically-resize-text-in-flutter – Rohith Nambiar Nov 25 '21 at 10:44
0

I have checked your code. You can do the following:

Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          GestureDetector(
                            onTap: () {
                              setState(() {
                                Navigator.of(context).pop();
                              });
                            },
                            child: Icon(
                              Icons.cancel,
                              color: Colors.black,
                            ),
                          ),
                          Expanded(
                            child: TextField(
                              maxLines: 4,
                              decoration: InputDecoration(
                                border: InputBorder.none,
                              ),
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                fontSize: 20,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ),
                          GestureDetector(
                              child: Icon(
                                Icons.delete_outline_rounded,
                                color: Colors.black,
                              ),
                              onTap: () {
                                print("Transazione Eliminata");

                                Navigator.of(context).pop();
                              }),
                        ],
                      ),
Md. Kamrul Amin
  • 1,870
  • 1
  • 11
  • 33
  • You forgot `controller: _titoloController,` in the TextField(), so i added it. I also want `maxLines: 1,`. Now it renders how i want it to be, but the text continues to disappear once it reaches the edge of the expanded. It becomes scrollable horizontally, but does not resize. – iocomxda Nov 25 '21 at 13:22
  • I also added two Spacer() one before Expanded(), another one after Expanded(). Because i want some gap before and after the Text that should be resized. Still need help in order to resize it, though. – iocomxda Nov 25 '21 at 13:29
  • if you add maxLines: 1, it will force the expanded widget to stay in a single line and you can scroll it. You should define the maxLines you want the widget to go. If you dont provide any maxLines, it will automatically resize to stay inside the widget even if it means the user has to scroll – Md. Kamrul Amin Nov 28 '21 at 06:29
  • I am not sure if i understood you correctly since i'm not native english. Are you suggesting me to remove the `maxLines` attribute? If i understood your comment correctly you are telling me that if i keep `maxLines: 1` my TextField will be scrollable (i don't want this), but if i remove the `maxLines` attribute it will resize. It Is correct? – iocomxda Nov 29 '21 at 14:50
  • Text size will not resize brother.. Maxlines just tells the Textfield to stay in a single line. You can check the following answer if you want to resize your textfield when user types a long text: https://stackoverflow.com/questions/51580658/flutter-textfield-how-to-shrink-the-font-if-the-text-entered-overflows – Md. Kamrul Amin Nov 29 '21 at 17:28