在 Flutter 中,我有一个表格,我试图在 TableCell 的下拉列表中获取列表。我创建了一个手势检测器来显示 Dailog,并使用 DropdownButtonForm 来显示列表和选择。但所选值未显示在 TableCell 中。我发现在下面的代码中,在容器中我没有将 selectedVal 的值设置为 true。
rows.add(
TableRow(
children: [
TableCell(
child: GestureDetector(
onTap: () {
showDialog(
context: context,
builder: (context) {
return StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return AlertDialog(
title: Text('Select Item'),
content: DropdownButtonFormField<String>(
value: selectedValue != '' ? selectedValue : null,
onChanged: (value) {
setState(() {
selectedValue = value!;
selectedVal = true;
});
},
items: itemList.map((item) {
return DropdownMenuItem<String>(
value: item,
child: Text(item),
);
}).toList(),
),
actions: <Widget>[
TextButton(
onPressed: () {
Navigator.of(context).pop();
setState(() {
selectedItem[rows.length - 1] = selectedValue;
});
print('selectedValue: $selectedValue');
print('selectedVal: $selectedVal');
},
child: Text('Ok'),
),
],
);
},
);
},
);
},
child: Container(
color: Colors.lightBlue,
child: Builder(
builder: (BuildContext context) {
return Column(
children: [
Text(
selectedVal ? selectedValue : 'Select Invoice',
style: TextStyle(
color: Colors.white,
),
),
],
);
},
),
),
),
),
您遇到的问题可能是由于当 selectedValue 更改时您没有更新 TableCell 内容。当 selectedValue 的值发生变化时,TableCell 小部件不会被重建,这就是更新的值没有反映在 TableCell 中的原因。
您可以使用 StatefulWidget 或 StatefulBuilder 包装您的 TableCell 小部件,也许这会对您有所帮助。
rows.add(TableRow(
children: [
TableCell(
child: GestureDetector(
onTap: () {
showDialog(
context: context,
builder: (context) {
return StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return AlertDialog(
title: Text('Select Item'),
content: DropdownButtonFormField<String>(
value: selectedValue != '' ? selectedValue : null,
onChanged: (value) {
setState(() {
selectedValue = value!;
selectedVal = true;
});
},
items: itemList.map((item) {
return DropdownMenuItem<String>(
value: item,
child: Text(item),
);
}).toList(),
),
actions: <Widget>[
TextButton(
onPressed: () {
Navigator.of(context).pop();
setState(() {
selectedItem[rows.length - 1] = selectedValue;
});
print('selectedValue: $selectedValue');
print('selectedVal: $selectedVal');
},
child: Text('Ok'),
),
],
);
},
);
},
);
},
child: Container(
color: Colors.lightBlue,
child: Builder(
builder: (BuildContext context) {
return Column(
children: [
Text(
selectedVal ? selectedValue : 'Select Invoice',
style: TextStyle(
color: Colors.white,
),
),
],
);
},
),
),
),
),
],
), );