I am using firebase realtime DB and I would like to fetch data based on categoryId.
Here's the Db structure.
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?
You can use the following plugin to fetch data from firebase:
Inside pubspec.yaml
:
dependencies:
firebase_database: ^4.1.1
firebase_core: ^0.5.0+1
in main()
function initialize 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
. For FutureBuilder
check:
https://flutter.dev/docs/cookbook.networking/fetch-data#5-display-the-data
https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html
I figured it out.
You make the URL data type final
and the URL becomes:
final url = 'https://mydburl.firebaseio.com/products.json?orderBy="categoryId"&equalTo="$id"';
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.