Firestoreドキュメントには、特定のユーザー情報(ユーザー名、年齢、課題など)が含まれています。もちろん、1人のユーザーが複数の課題に直面する可能性があります。特定のユーザーデータをオブジェクトのリストにロードしていますが、そのリストをFutureBuilderに返すと問題が発生します。2人のユーザーがいて、それぞれに3つの課題があるとします。リストを返すと、正しい長さ(6)が表示されますが、リストにロードされた最後のユーザーからのデータのみが含まれています。私のListView.builderは6つの_cardBuildersを表示しますが、それらのカードのデータは同じです。
コンストラクターのリストをMapのリストに置き換えようとしましたが、結果は同じです。おそらく論理的な間違いですが、私はそれを見つけることができません。
Future<List<AllChallengesStorage>> challengesToFeed () async {
var queryResult = await Firestore.instance.collection("Users")
.where("total_challenges", isGreaterThanOrEqualTo: 1)
.getDocuments();
if (queryResult.documents.isNotEmpty){
for (int i=0; i < queryResult.documents.length; ++i){
for (int j=0; j < queryResult.documents[i].data['total_challenges']; ++j){
widget.challengesInfo.username = queryResult.documents[i].data['username'];
widget.challengesInfo.name = queryResult.documents[i].data['challenges'][j]['name'];
widget.challengesInfo.description = queryResult.documents[i].data['challenges'][j]['description'];
widget.challengesInfo.duration = queryResult.documents[i].data['challenges'][j]['duration'];
allChallenges.add(widget.challengesInfo);
}
}
}
return allChallenges;
}
class _FeedState extends State<Feed> {
List<AllChallengesStorage> allChallenges = [];
@override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder<List<AllChallengesStorage>>(
future: challengesToFeed(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (!snapshot.hasData) return Center(child: Text("Loading..."));
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) {
return _cardBuilder(context, snapshot, index);
},
);
},
),
);
}
問題は、同じオブジェクトを使用していて、各ループでそのプロパティを上書きしていることです。必要なのは、2番目のループが完了するたびに、モデルクラスで新しいヘルパーオブジェクトを作成するなど、新しいカードごとに新しいオブジェクトをインスタンス化することです。
for (int i=0; i < queryResult.documents.length; ++i){
ClassName helper = ClassName();
for (int j=0; j < queryResult.documents[i].data['total_challenges']; ++j){
helper.username = queryResult.documents[i].data['username'];
helper.name = queryResult.documents[i].data['challenges'][j]['name'];
helper.description = queryResult.documents[i].data['challenges'][j]['description'];
helper.duration = queryResult.documents[i].data['challenges'][j]['duration'];
allChallenges.add(helper);
}
}
}
次に、リスト内のオブジェクトにアクセスするために、インデックスを指定し、そのインデックスとそのプロパティでオブジェクトにアクセスできます。
allChallenges[index].name
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加