Home > Back-end >  update TextFormField on pressing button
update TextFormField on pressing button

Time:03-29

I have a beginner question. I don't understand why TextFormField is not updated in this example on pressing the FloatingActionButton. _counter field is incremented inside of setState. Text widget is updated as expected.
I see this difference: Text is stateless and TextFormField statefull widget.
What should I do to show the correct value also inside TextFormField?

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

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

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: 'Flutter Demo',
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);
  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter  ;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'Your number:',
            ),
            TextFormField(
              keyboardType: const TextInputType.numberWithOptions(
                signed: false,
                decimal: false,
              ),
              initialValue: (_counter.toString()),
              onChanged: (val) {
                setState(() {
                  _counter = int.parse(val);
                });
              },
            ),
            Text(
              '$_counter',
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}

Thank you
Qjeta

CodePudding user response:

Welcome To Flutter

initialValue set value on time when the widget is build, you need to use something else to update the textfield. here is the complete code that works as you want.

You have to use the TextEditingController and remove the initialValue

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

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

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return  MaterialApp(
      title: 'Flutter Demo',
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
   MyHomePage({Key? key, required this.title}) : super(key: key);
  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  TextEditingController myController = TextEditingController();


  @override
  void initState() {
    super.initState();
    myController.text=_counter.toString();
  }

  void _incrementCounter() {
    setState(() {
      _counter  ;
      myController.text=_counter.toString();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'Your number:',
            ),
            TextFormField(
              controller: myController..text,
              keyboardType: const TextInputType.numberWithOptions(
                signed: false,
                decimal: false,
              ),
              // initialValue: (_counter.toString()),
              onChanged: (val) {
                setState(() {
                  _counter = int.parse(val);
                });
              },
            ),
            Text(
              '$_counter',
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}

CodePudding user response:

Problem :
the argument initialValue can take one value only for the first time

Solution ^^

Use TextEditingController instead

 class HomePage extends StatefulWidget {
 const HomePage({Key? key}) : super(key: key);

  @override
 State<HomePage> createState() => _HomePageState();
  }

 class _HomePageState extends State<HomePage> {
   int _counter = 0;

     TextEditingController _textEditingController =new 
   TextEditingController();
  void _incrementCounter() {
     setState(() {
  _counter  ;
   });
_textEditingController.text = _counter.toString();
  }

  @override
  Widget build(BuildContext context) {
return Scaffold(
  appBar: AppBar(
    title: Text("test"),
  ),
  body: Center(
    child: Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        const Text(
          'Your number:',
        ),
        TextFormField(
          keyboardType: const TextInputType.numberWithOptions(
            signed: false,
            decimal: false,
          ),
          controller: _textEditingController,
        ),
        Text(
          '$_counter',
        ),
      ],
    ),
  ),
  floatingActionButton: FloatingActionButton(
    onPressed: _incrementCounter,
    tooltip: 'Increment',
    child: const Icon(Icons.add),
  ),
);
 }
  }
  • Related