[英]Fetching data from firebase based on foreign key
I am using firebase realtime DB and I would like to fetch data based on categoryId.我正在使用 firebase 实时数据库,我想根据 categoryId 获取数据。
Here's the Db structure.这是 Db 结构。
Here's the code:这是代码:
Future<void> fetchAndSetProducts(String id) async {
const url = 'https://random-9006.firebaseio.com/products.json';
try {
final response = await http.get(url);
final extractedData = json.decode(response.body) as Map<String, dynamic>;
print(extractedData.toString());
}
How to construct the URL in order to get the products per the categoryId passed?如何构造 URL 以获取每个传递的 categoryId 的产品?
You can use the following plugin to fetch data from firebase:您可以使用以下插件从 firebase 中获取数据:
Inside pubspec.yaml
:在
pubspec.yaml
内部:
dependencies:
firebase_database: ^4.1.1
firebase_core: ^0.5.0+1
in main()
function initialize Firebase:在
main()
function 中初始化 Firebase:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
Then you can get the data using the following way:然后您可以使用以下方式获取数据:
Future<DataSnapshot> getData(String category){
var dbRef = FirebaseDatabase.instance.reference().child("products");
return await dbRef.orderByChild("categoryId").equalTo(category).once();
}
You can then call this future
method inside a FutureBuilder
.然后,您可以在
FutureBuilder
中调用这个future
方法。 For FutureBuilder
check:对于
FutureBuilder
检查:
https://flutter.dev/docs/cookbook.networking/fetch-data#5-display-the-data https://flutter.dev/docs/cookbook.networking/fetch-data#5-display-the-data
https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html
I figured it out.我想到了。
You make the URL data type final
and the URL becomes:您将 URL 数据类型设为
final
类型,URL 变为:
final url = 'https://mydburl.firebaseio.com/products.json?orderBy="categoryId"&equalTo="$id"';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.