此下拉列表将从将来的构建器中获取其项目 但是从列表中选择一个项目后,它不会更改所选项目,我相信这是因为我没有使用常规字符串或int项目
FutureBuilder(
future: getCategories(http.Client()),
builder: (BuildContext context, AsyncSnapshot<List<Categories>> snapshot) {
if (!snapshot.hasData) return CircularProgressIndicator();
selectedCategory = snapshot.data[0].id;
if (snapshot.hasData) {
this.categoriesList = snapshot.data;
if (this.categoriesList.length > 0) {
return DropdownButton<int>(
value: selectedCategory,
onChanged: (int newValue) {
setState(() {
selectedCategory = newValue;
this.eventOpj.categoryId = newValue;
});
},
items: snapshot.data
.map<DropdownMenuItem<int>>((Categories catg) {
return DropdownMenuItem<int>(
value: catg.id,
child: Text(catg.nameEn),
);
}).toList(),
);
} else {
return Text('data');
}
}
},
),
答案 0 :(得分:0)
我认为这是因为您在构建方法中加入了逻辑 。
def myview(request):
# if you have variables that you want to always
# be in the context, the safest way is to define
# them right from the start (with a dummy value):
name = None
# now FIRST test the request method:
if request.method == "POST":
# and ONLY then build a bound form:
form = MyForm(request.POST)
if form.is_valid():
# use sanitized data, not raw POST data:
name = form.cleaned_data["name"]
else:
# build an unbound form
form = MyForm()
# here you know that both variables have been defined whatever
return render(request, "mytemplate.html", {"form": form, "name": name}
使逻辑脱离构建方法,如果需要在接收数据时应用逻辑,则应在有状态小部件的initState中调用此方法。
答案 1 :(得分:0)
您可以仅在initState()
中进行一次future调用,将future设置为_future
变量,然后在FutureBuilder
上使用该变量,如下所示:
@override
void initState() {
super.initState();
_future = getCategories(http.Client());
}
FutureBuilder(
future: _future,
...
此外,selectedCategory = snapshot.data[0].id;
行仅应在第一次加载结果时执行,因为这只是选择DropdownButton
的第一个元素。您可以将该行放在if (selectedCategory == null)