flutter Textfiled进行不必要的重建



我在MultiPageForm中有一个ListBuilder,它在每个"添加"按钮上创建一个带有2个文本字段的卡片。它过去工作得很好,但现在不行了——每次按下TextField时,页面都会重新构建,键盘一打开就关闭。

List<AddIngredientItem> basic_ingredients = [];

这是ListBuilder

ListView.builder(
physics: NeverScrollableScrollPhysics(),
shrinkWrap: true,
itemCount: basic_ingredients.length,
itemBuilder: (BuildContext context, index) {
return Dismissible(
background: slideBackground("right"),
secondaryBackground: slideBackground("left"),
key: UniqueKey(),
onDismissed: (direction) {
setState(
() {
basic_ingredients.removeAt(index);
},
);
},
child: basic_ingredients[index]);
},
),

这是创建具有2个文本字段的卡片的类:

import 'package:flutter/material.dart';
class AddIngredientItem extends StatefulWidget {
final _ingi_name_controller = TextEditingController();
final _ingi_amount_controller = TextEditingController();
final _measurement_controller = TextEditingController();
AddIngredientItem();
@override
String toStringShort() {
return _ingi_name_controller.text;
}
@override
_AddIngredientItemState createState() => _AddIngredientItemState();
}
class _AddIngredientItemState extends State<AddIngredientItem> {
List _measurements = ["1", "2", "3", "4", "5"];
List<DropdownMenuItem<String>> _dropDownMenuItems;
List<DropdownMenuItem<String>> getDropDownMenuItems() {
List<DropdownMenuItem<String>> items = new List();
for (String city in _measurements) {
items.add(new DropdownMenuItem(value: city, child: new Text(city)));
}
return items;
}
@override
void initState() {
_dropDownMenuItems = getDropDownMenuItems();
super.initState();
}
@override
Widget build(BuildContext context) {
return Card(
child: Padding(
padding: const EdgeInsets.all(5.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Expanded(
child: TextFormField(
controller: widget._ingi_name_controller,
maxLines: 1,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 18.0,
),
onChanged: (val) {
setState(() {});
},
decoration: InputDecoration(
border: UnderlineInputBorder(
borderSide:
BorderSide(color: Theme.of(context).primaryColor),
),
hintText: 'hint',
),
),
),
Flexible(
child: TextFormField(
controller: widget._ingi_amount_controller,
keyboardType: TextInputType.number,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 18.0,
),
maxLines: 1,
onChanged: (val) {
setState(() {});
},
decoration: InputDecoration(
border: UnderlineInputBorder(
borderSide:
BorderSide(color: Theme.of(context).primaryColor),
),
hintText: 'amount',
),
),
),
Flexible(
child: DropdownButton(
hint: Center(
child: Text("unit", style: TextStyle(fontSize: 18))),
value: widget._measurement_controller.text == ""
? null
: widget._measurement_controller.text,
items: _dropDownMenuItems,
onChanged: (val) {
widget._measurement_controller.text = val;
setState(() {});
},
)),
],
),
),
);
}
}

这个问题只是关于TextField,有什么关于如何使其工作的建议吗?

问题出现在Unique中。将其更改为ValueKey有帮助。

相关内容

  • 没有找到相关文章

最新更新