gpt4 book ai didi

flutter - 使用 initialValue 时 setState 不会更新 TextFormField

转载 作者:行者123 更新时间:2023-12-04 11:06:29 27 4
gpt4 key购买 nike

每个人。

我正在使用没有任何自己的 TextEditController 的 Form 和 TextFieldForm。有 3 个带有初始值的 TextFieldForm (Value_1, Value_2, Total)。当我编辑第一个时,总文本字段应包含计算结果。要更新小部件,我正在使用 setState。变量_total 和Text 小部件始终有正确的计算值,但Total 文本字段不想更新的问题。

为什么?可以不使用自己的 TextEditController 吗?

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: TestForm(),
);
}
}

class TestForm extends StatefulWidget {
@override
_TestFormState createState() => _TestFormState();
}

class _TestFormState extends State<TestForm> {
GlobalKey<FormState> _formKey = GlobalKey();

int _value1 = 0;
int _value2 = 20;
int _total = 0;

@override
Widget build(BuildContext context) {
print('rebuild');
return Scaffold(
appBar: AppBar(title: Text('test form')),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Form(
key: _formKey,
child: ListView(
children: <Widget>[
TextFormField(
initialValue: _value1.toString(),
decoration: InputDecoration(
labelText: 'Value_1',
),
keyboardType: TextInputType.number,
onChanged: (value) {
setState(() {
_total = int.parse(value) * _value2;
print('total: ' + _total.toString());
});
},
),
TextFormField(
initialValue: _value2.toString(),
keyboardType: TextInputType.number,
decoration: InputDecoration(
labelText: 'Value_2',
),
),
TextFormField(
initialValue: _total.toString(),
keyboardType: TextInputType.number,
decoration: InputDecoration(
labelText: 'Total',
),
),
SizedBox(height: 20),
Text('total: ' + _total.toString()),
],
),
),
),
);
}
}



example

最佳答案

如果你有一个 react 数据源,也就是可以根据网络更新或其他数据改变的数据,一个对我有用的黑客是使用 Key .
通过制作 Key在 react 数据( toString() )中,表单字段每次都会更改 Key变化。
所以在这种情况下你可以这样做:

TextFormField(
key: Key(_total.toString()), // <- Magic!
initialValue: _total.toString(),
keyboardType: TextInputType.number,
decoration: InputDecoration(
labelText: 'Total',
),
),

关于flutter - 使用 initialValue 时 setState 不会更新 TextFormField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58053956/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com