简体   繁体   English

按下按钮更新 TextFormField

[英]update TextFormField on pressing button

I have a beginner question.我有一个初学者的问题。 I don't understand why TextFormField is not updated in this example on pressing the FloatingActionButton.我不明白为什么在此示例中按下 FloatingActionButton 时 TextFormField 没有更新。 _counter field is incremented inside of setState. _counter 字段在 setState 内部递增。 Text widget is updated as expected.文本小部件按预期更新。
I see this difference: Text is stateless and TextFormField statefull widget.我看到了这个区别:文本是无状态的,而 TextFormField 是有状态的小部件。
What should I do to show the correct value also inside TextFormField?我应该怎么做才能在 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捷达

Welcome To Flutter欢迎拨打Flutter

initialValue set value on time when the widget is build, you need to use something else to update the textfield. initialValue 在构建小部件时按时设置值,您需要使用其他东西来更新文本字段。 here is the complete code that works as you want.这是您想要的完整代码。

You have to use the TextEditingController and remove the initialValue您必须使用 TextEditingController 并删除 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),
      ),
    );
  }
}

Problem:问题:
the value of the "initialValue" argument can not be changed “initialValue”参数的值不能改变

Solution ^^解决方案^^

Use TextEditingController instead改为使用 TextEditingController

 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),
  ),
);
 }
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM