我只想顯示包含數字 1 的帖子。
JSON:
posts = '{"number":"1"}';
JSON 是在一個單獨的檔案中獲取的,例如:
Posts(Map<String, dynamic> json) : super(json) {
posts = json["number"];
}
我有這個:
Widget _buildGridView() => StreamBuilder<List<Posts>?>(
builder: (context, snapshot) {
if (snapshot.data != null) {
return new GridView.count(
children: List.generate(snapshot.data!.length, (index) {
return _buildPlacesCell(snapshot.data![index]);
}));
}
});
我想知道:我可以做這樣的事情嗎?
if (snapshot.data.posts.number = 1)
代替
snapshot.data != null
或不?
僅當帖子的 JSON 檔案中的數字為 1 時,我才想顯示我的資料,但我無法使其正常作業。
我收到以下錯誤:
error: The getter 'posts' isn't defined for the type 'List<Post>'
編輯:在 Jamiu 的片段之后,出現以下錯誤:
錯誤:未為型別“Post”定義運算子“[]”。
和:
錯誤:主體可能正常完成,導致回傳 'null',但回傳型別可能是不可為空的型別
uj5u.com熱心網友回復:
您可以嵌套 if 陳述句。首先,檢查 ifsnapshot.data != null然后在 if 陳述句中,檢查是否snapshot.data.posts.number = 1像這樣:
if(snapshot.data!=null){
if(snapshot.data.posts.number=1){
return new GridView.count(
children: List.generate(snapshot.data!.length, (index) {
return _buildCell(snapshot.data![index]);
}));
}
}
考慮這樣做:
StreamBuilder<List<Place>>(
stream: listPosts,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(child: CircularProgressIndicator());
}
if (snapshot.hasData) {
final data = snapshot.data!;
if (data.isNotEmpty) {
return GridView.count(
children:[
for(var post in data)
if (post.number == '1') _buildPlacesCell(post);
],
);
}else{
return const Center(
Text('No posts to display');
);
}
}
if (snapshot.hasError) {
print(snapshot.error);
//! do any error handling here
}
return const Center(child: CircularProgressIndicator());
},
),
uj5u.com熱心網友回復:
//嘗試這個
Map<String, dynamic> data = snapshot.data!.data() as Map<String, dynamic>;
if(data["number"]=="1"){
//do
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/359671.html
標籤:json WordPress的 扑 休息 镖
