如何将值从初始状态传递到flutter中的小部件



在我的应用程序中,我对initstate进行了一个api调用,我能够检索响应数据

void initState() {
super.initState();
_dbHelper.getAllUserData().then((value)async{
userdetails = value;
await getsubjectList(value[0].userId!, value[0].accountId!).then((value){
testfunction(value);
});
});
} 

我需要将其响应传递给ListViewBuilder以显示应用程序上的值,我如何实现这一点?

在类中声明一个列表:

List<YourObject> list = [];

设置列表中的值(最好创建一个填充列表的函数:

fetchData() {
List<YourObject> tempList = ... get the data ...;
setState(() { list = tempList; });
}

在你的initState()中调用fetchData

然后创建ListView:

ListView.builder(
itemCount: list.length,
physics: AlwaysScrollableScrollPhysics()
itemBuilder: (context, index){
return ListTile(
title: Text("${list[index].toString()}")
);
}
),

我也希望你有一个有状态的小部件,而不是无状态的。

首先在itemCount中调用列表的长度,这里我返回ListTile列表构建器,您可以更改它的自定义设计:

初始化部分:

List<YourModelClass> subjectList = [];
void initState() {
super.initState();
_dbHelper.getAllUserData().then((value)async{
userdetails = value;
// subjectList.add(value); // store the user item 
await getsubjectList(value[0].userId!, value[0].accountId!).then((value){
testfunction(value);
});
});
} 

身体:

body: ListView.builder(
itemCount: subjectList.length,
shrinkWrap: true,
physics: ScrollPhysics()
itemBuilder: (BuildContext context,int index){
return ListTile(
title:Text("${subjectList[index].itemName}")
);
}
),

1-创建私有变量var _response;

2-在你的initState中设置一个值给你的_response使用setState

@override
void initState() {
super.initState();
setState(() {
_response = yourApiResponse;
});
}
3-使用_response在你的listView中。构建器部件
body: ListView.builder(
itemCount: _response.length,
itemBuilder: (context,index){
return ListTile(
title:Text(_response[index].Name)
);
}
),

最新更新