How to change TextFormField initialValue dynamically?

668

You can use TextEditingController in this case.

TextEditingController _controller = TextEditingController();

Consumer<ButtonMode>(builder: (context, buttonMode, child) {

        if(buttonMode.weight != null && _controller.text != buttonMode.weight){ // or check for the null value of button mode.weight alone
             _controller.text = buttonMode.weight ?? '' ;
        }
        return TextFormField(
            controller : _controller,
            validator: (value) {
              if (value == null || value.isEmpty) {
                return 'Please enter weight';
              }
              return null;
            },
         
              );
    });
Share:
668
João Pedro
Author by

João Pedro

Updated on December 31, 2022

Comments

  • João Pedro
    João Pedro over 1 year

    I'm trying to use a value from a provider model to update the initialValue of a TextFormField, but the initialValue doesn't change.

    
    import 'package:flutter/material.dart';
    import 'package:new_app/models/button_mode.dart';
    import 'package:provider/provider.dart';
    
    class EditWeightTextField extends StatelessWidget {
    
    
      const EditWeightTextField(
          {Key? key})
          : super(key: key);
    
      @override
      Widget build(BuildContext context) {
      
        return Consumer<ButtonMode>(builder: (context, buttonMode, child) {
            return TextFormField(
                initialValue: buttonMode.weight.toString(),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return 'Please enter weight';
                  }
                  return null;
                },
             
                  );
        });
      }
    }
    
    

    if instead of a TextFormField I use a Text(${buttonMode.weight}') then the text is updated properly. What can I do to make it work with the TextFormField?

    • HaSnen Tai
      HaSnen Tai over 2 years
      I would recommend you to use TextEditingController(text: 'Initial value'); , Let me know if you need a complete solution
    • João Pedro
      João Pedro over 2 years
      I would appreciate a complete solution