我有一個函式,它需要一些 json 并將整個物件放入動態串列中。我無法使用 futurebuilder 回圈遍歷該串列。我總是得到“沒有為類 'Future<List> 定義 getter 'length'”錯誤。標題相同。
這樣做的正確方法是什么?在 futurebuilder 或 listbuilder 中訪問此串列。
提前非常感謝。
class _HomeScreenState extends State<HomeScreen> {
final storage = new FlutterSecureStorage();
Future<List<dynamic>> _loadedProducts;
@override
void initState() {
_loadedProducts = _getPolicy();
super.initState();
}
Future<void> _getPolicy() async {
final url = Uri.parse('https://jsonplaceholder.typicode.com/todos/1');
try {
final response = await http.get(url);
final extractedData = json.decode(response.body);
final List<dynamic> loadedProducts = [];
extractedData.forEach((prodId, prodData) {
loadedProducts.addAll(extractedData);
});
_loadedProducts = loadedProducts;
print(_loadedProducts);
} catch (error) {
print('---error-');
throw (error);
}
}
這是futurebuilder的代碼
FutureBuilder<List<dynamic>>(
future: _loadedProducts,
builder: (context, snapshot) {
if (snapshot.hasData) {
return AnimatedList(
initialItemCount: snapshot.data.length,
itemBuilder:
(BuildContext context, int index,
Animation animation) {
return new Text(_loadedProducts.title.toString());
},
);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
// By default, show a loading spinner.
return CircularProgressIndicator();
},
);
uj5u.com熱心網友回復:
您需要在_getPolicy()將來的函式中回傳串列。所以嘗試像這樣改變它:
Future<List<dynamic>> _getPolicy() async {
final url = Uri.parse('https://jsonplaceholder.typicode.com/todos');
try {
final response = await http.get(url);
return json.decode(response.body);
} catch (error) {
print('---error-');
rethrow;
}
}
我所做的更改:在您的網址中,您只有一個待辦事項,因此我/1從您的網址中洗掉了。相反,如果您想獲取用戶的所有待辦事項,userId=1則可以將 url 更改為以下內容
https://jsonplaceholder.typicode.com/todos?userId=1
此外,json.decode()已經回傳一個串列,所以不需要你的forEach
此外,您需要修復影片串列中的文本小部件,因為您無法使用_loadedProducts.title. 您需要在此處使用快照資料。這是經過一些修復后的 FutureBuilder 代碼:
FutureBuilder<List<dynamic>>(
future: _loadedProducts,
builder: (context, AsyncSnapshot<List<dynamic>> snapshot) {
if (snapshot.hasData && snapshot.data != null && snapshot.data!.isNotEmpty) {
return AnimatedList(
initialItemCount: snapshot.data!.length,
itemBuilder:
(BuildContext context, int index,
Animation animation) {
return new Text(snapshot.data![index]['title']);
},
);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
// By default, show a loading spinner.
return CircularProgressIndicator();
},
);
這是一個作業演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/407421.html
標籤:
上一篇:如何在R中輸出一個串列
