选择新值后 Flutter DropDownButton 值不会改变

问题描述

我一直在尝试制作一个外部 UI,用户可以使用它对云中的数据库 (dynamodb) 进行某些更改。当我选择一个新值时,我希望它显示用户想要进行的更改,而不实际更改数据库。仅当我按下应用栏上的按钮时才会保存更改。此外,当我使用 setState 重建按钮时,云上的值不会更改,它还会更改列中所有按钮的值(没有 setState 也能正常工作)。当我按下保存图标时,我提供的代码会更改数据库,但下拉按钮的值保持不变,除非我刷新页面。如果我没有足够清楚地解释我的问题,我深表歉意,这是我第一次在 Stackoverflow 上发帖,我仍在学习如何使用 Flutter 和 aws amplify。

body: InteractiveViewer(
    constrained: false,child: DataTable(
        columns: [
          DataColumn(label: Text('Apt #')),DataColumn(label: Text('Type')),DataColumn(label: Text('Availability')),DataColumn(label: Text('Price')),DataColumn(label: Text('Area'))
        ],rows: aprts.map<DaTarow>((element) { //aprts is a list that contains apartment objects.
          return DaTarow(cells: [
            DataCell(Text(element.aptNum.toString())),DataCell(Text(element.type)),DataCell(DropdownButton<String>( /// this is the part im having problems wi
              value: element.availabily,// gets the value for the availability attribute for the element and stores it into value.
              onChanged: (String newValue) {
                availValue = newValue; //stores the newValue in a global variable that is used in a function that is used toactually make changes to the database.
                tempAvail = element;
                
              },items: <String>['AVAILABLE','SOLD','RESERVED']
                  .map((String value) {
                return DropdownMenuItem<String>(
                  value: value,child: Text(value),);
              }).toList(),)),// end of problem. 
            DataCell(TextField(
              controller: TextEditingController()
                ..text = element.price.toString(),onChanged: (text) {
                aptPrice = text;
                tempPrice = element;
              },DataCell(TextField(
              controller: TextEditingController()..text = element.area,onChanged: (text) {
                aptArea = text; 
                tempArea = element;
              },]);
        }).toList()),),

What the app looks like. After pressing the button

解决方法

使用

onChanged: (String newValue) {
                setState(() {
                   availValue = newValue; 
                   tempAvail = element;
                  }
                 )
                },

因为对于 UI 中的每个更改,您都必须调用 setState((){})