'Flutter Firestore - Load insted references in same model
My project has a document with two or more references, sometimes I need to load these references data before display the data itself.
For example:
"Item" document has: userRef
, UniversityRef
.
I can load item without problem, but I can't understand how can load userRef
and uniRef
datas!
I am using a FirestoreListView
Widget.
This is my code.
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:flutterfire_ui/firestore.dart';
import 'package:uobbook/models/item.dart';
import 'package:uobbook/services/firestore-reference-load.dart';
import 'package:uobbook/widgets/list_view_items.dart';
import '../models/college.dart';
import '../models/user.dart';
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
int tabIndexSelected = 0;
String pageTitle = "Home Page";
void onItemTapped(int index) {
setState(() {
tabIndexSelected = index;
});
}
final itemsQuery = FirebaseFirestore.instance
.collection('items')
.orderBy('dateTime')
.withConverter<Item>(
fromFirestore: (snapshot, _) => Item.fromJson(snapshot.data()),
toFirestore: (item, _) => item.toJson(),
);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
this.pageTitle,
style: TextStyle(color: Colors.black),
),
backgroundColor: Colors.white70,
),
body: FirestoreListItems(itemsQuery: itemsQuery),
);
}
}
class FirestoreListItems extends StatelessWidget {
const FirestoreListItems({
Key key,
@required this.itemsQuery,
}) : super(key: key);
final Query<Item> itemsQuery;
@override
Widget build(BuildContext context) {
return FirestoreListView<Item>(
query: itemsQuery,
itemBuilder: (context, snapshot) {
Item item = snapshot.data();
return ListTile(
//-- list to present all data of college, university and
onTap: () => {print("tapped")},
title: Text(item.title),
subtitle: Text(
"Subtitle here",
overflow: TextOverflow.ellipsis,
maxLines: 1,
softWrap: false,
),
leading: Icon(Icons.label),
trailing: Column(
children: [
Icon(Icons.payment),
Text(
"15BD",
style: TextStyle(color: Colors.black45),
),
],
),
);
},
);
}
}
Solution 1:[1]
userRef data and uniRef data are in different collections. You should use multiple queries to load data from different collections.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Daham Akalanka |