Search code examples
flutterdarttextformfieldflutter-alertdialogflutter-textformfield

Flutter: How to change variables through TextFormField in a AlertDialog?


I want to implement a function as following: There is a button named 自定义. In this page, there is a variable named money. When I click the button, an AlertDialog with a TextFormField inside will occur. I hope that after inputting a number X into the TextFormField and clicking button ok to exit the AlertDialog, money would be changed to X. I have used onSaved to save the variable, and used _formkey.currentState.save(), but money didn't change. What's wrong with my codes? Here are my codes:

void _showMessageDialog() {
    //int addMoney = 0;
    showDialog(
      context: context,
      builder: (BuildContext context) {
        // return object of type Dialog
        return AlertDialog(
          key: _formKey,
          title: new Text('INPUT'),
          content: TextFormField(
            maxLines: 1,
            keyboardType: TextInputType.emailAddress,
            autofocus: false,
            style: TextStyle(fontSize: 15),
            decoration: new InputDecoration(
                border: InputBorder.none,
                hintText: 'input',
            ),
            onSaved: (value) {
              money = int.parse(value?.trim() ?? '0') as double;
              print(money);
            }
          ),
          actions: <Widget>[
            new TextButton(
              key: _formKey,
              child: new Text("ok"),
              onPressed: () {
                _formKey.currentState?.save();
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }

Here are the codes relative to the button 自定义

OutlinedButton(
                                style: OutlinedButton.styleFrom(
                                  side: BorderSide(
                                    width: 1,
                                    color: Colors.blueAccent
                                  )
                                ),
                                onPressed: () {
                                  // Navigator.of(context).push(
                                  //   _showMessageDialog()
                                  // );
                                  _showMessageDialog();
                                },
                                child: Text(
                                  "自定义",
                                  style: TextStyle(
                                    fontSize: 20,
                                    fontWeight: FontWeight.w700,
                                    color: Colors.blueAccent
                                  ),
                                ),
                              ),

I know maybe I have made a big mistake, but it is my first Flutter project. Thanks for your advices.


Solution

  • I would use ValueNotifier for this. But first you need to add a controller to your TextFormField so you can get the text user typed in.

    //initialize it
    final myController = TextEditingController();
    
    TextFormField(
      controller: myController, //pass it to the TextFormField
    ),
    
    TextButton(
      child: new Text("ok"),
      onPressed: () {
        String input = myController.text; //this is how you get the text input
        _formKey.currentState?.save();
        Navigator.of(context).pop();
      },
    ),
    

    As I said you also need to initialize ValueNotifier and pass it to _showMessageDialog

    ValueNotifier<int> money = ValueNotifier(0);
    _showMessageDialog(money); //and pass it to your function
    
    void _showMessageDialog(ValueNotifier<int> money) {
      TextButton(
        child: new Text("ok"),
        onPressed: () {
          String input = myController.text; //this is how you get the text input
          money.value = int.parse(input); //and then update your money variable
          _formKey.currentState?.save();
          Navigator.of(context).pop();
        },
      ),
    }