按下按钮更新 TextFormField

update TextFormField on pressing button

我有一个新手问题。 我不明白为什么在此示例中按下 FloatingActionButton 时 TextFormField 没有更新。 _counter 字段在 setState 内部递增。文本小部件按预期更新。
我看到了这个区别:文本是无状态的,而 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),
      ),
    );
  }
}

谢谢
齐杰塔

欢迎使用 Flutter

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

问题:
“initialValue”参数的值无法更改

解决方法^^

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