Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter Text will not update further after Textfield input

Tags:

flutter

dart

I have arrow buttons to increase or decrease a variable age which work fine to update the hintText, but if I use the TextField widget to input a new value, it updates just fine, but after that the arrow buttons no longer function to further alter the age value in the hintText.

However, the value is still being updated behind the scenes and can be viewed with a print function.

Here's a simplified version of the code used:

TextField(
    onChanged: (val) {
          setState(() {
            age = int.parse(val);
          });,
    keyboardType: TextInputType.number,
    decoration: InputDecoration(
    border: InputBorder.none,
    hintText: age.toString(),
    hintStyle: TextStyle(
        color: Color(0xFF999999), fontWeight: FontWeight.bold),
  ),
)


Container(
      child: RawMaterialButton(
        onPressed: chngAge,
)


void chngAge() {
    setState(() {
      age++;
    });
  }

I'm wondering if after some text has been input into a text field that it is not longer hintText and thus cannot be updated in this way?

like image 621
Hasen Avatar asked Oct 16 '25 14:10

Hasen


1 Answers

What you need is changing the data of your TextField not the hint value, because when you write some text into your TextField, the hint disappears.

Here is an example I made :

class SampleText extends StatefulWidget {
  @override
  _SampleTextState createState() => _SampleTextState();
}

class _SampleTextState extends State<SampleText> {
  TextEditingController _controller = TextEditingController();

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.plus_one),
        onPressed: chngAge,
      ),
      body: Center(
        child: TextField(
          controller: _controller,
          keyboardType: TextInputType.number,
          decoration: InputDecoration(
            border: InputBorder.none,
            hintStyle: TextStyle(
                color: Color(0xFF999999), fontWeight: FontWeight.bold),
          ),
        ),
      ),
    );
  }

  void chngAge() {
    _controller.text = (int.parse(_controller.text) + 1).toString();
  }
}

You can get more info here: https://flutter.dev/docs/cookbook/forms/retrieve-input

like image 85
diegoveloper Avatar answered Oct 18 '25 07:10

diegoveloper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!