我们正在运行一个flutter-project,并希望包含一个带dropdownmenu的有状态小部件。我们使用SQflite作为我们的数据库。
我们在数据库中有一个配置文件列表,并通过下拉菜单选择一个配置文件。这很好。
问题:
我们使用SharedPreferences保存最后选择的配置文件的ID。最初,我们希望将配置文件的最后一个选定ID(我们从SharedPreferences中加载)作为默认值。
我们的future-builder(列表类型为profilesFuture
的Future<List<Profile>>
)内的Dropdown-Menu:
return new Container(
child: DropdownButton<Profile>(
items: snapshot.data.map((Profile item) {
return DropdownMenuItem<Profile>(
value: item,
child: Text(item.caption + " (" + item.serverAddress + ")")
);
}).cast<DropdownMenuItem<Profile>>().toList(),
onChanged: (Profile newSelectedProfile) {
setState(() {
selectedProfile = newSelectedProfile;
PreferencesService.setLastProfileId(newSelectedProfile.id);
});
},
value: selectedProfile,
)
);
我们这样初始化状态:Future profilesFuture;
Profile selectedProfile;
Future prefService;
int lastProfileId;
@override
void initState() {
profilesFuture = DatabaseService.db.getProfiles();
super.initState();
_getLastProfileId().then((value) => _getSelectedProfile(value));
}
Future<Profile> _getSelectedProfile(int id) async {
Profile profile = await DatabaseService.db.getProfileById(id);
setState(() {
selectedProfile = profile;
});
return profile;
}
Future<int> _getLastProfileId() async {
int profileId = await PreferencesService.getLastProfileId();
setState(() {
lastProfileId = profileId;
});
return profileId;
}
错误either zero or 2 or more dropdownmenuitems were detected with the same value. Assertion failed. There should be exactly one item with DropDownMenus value.
更多信息:https://github.com/glutter-dev-team/glutter/blob/feature/profile-selector/lib/widgets/profile_selector.dart问题
它出什么问题了?如何使用异步值正确初始化DropDownMenu。该问题肯定是由默认值引起的。如果不初始化值参数,它将正常工作,但是初始状态不正确。
我们要做的就是:
最佳答案
引用@pskink,这是解决了我们问题的解决方案:
我们已经在数据模型==
中覆盖了默认的Profile
操作。
bool operator == (dynamic other) =>
other != null && other is Profile && this.id == other.id;
@override
int get hashCode => super.hashCode;
关于flutter - Flutter DropDownMenu:初始化异步默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64659537/