Home > Software engineering >  Flutter: Firebase Query with Class and it don't excute print function inside the map
Flutter: Firebase Query with Class and it don't excute print function inside the map

Time:06-21

Some actions I did as below:

  1. defining a class called ProductModel
  2. added two documents in the collection of "product model"
  3. have a function called getMessagesTestTest(), it will be triggered when I push the button.

When I pushed that button to execute getMessagesTestTest(), however, it didn't run the following itmes.

  1. print("start in loop");
  2. print('doc.id == ${doc.id}');

Maybe something I didn't know to implement or assign properly caused this problem.

Document1 enter image description here

Document2 enter image description here

Print window enter image description here

Source Code: defining function

  void getMessagesTestTest() async{

    final aa = await _firestore.collection('ProductModel').snapshots().map((notes){
      notesFromFirestore.clear();
      for(final DocumentSnapshot<Map<String,dynamic>> doc in notes.docs){
        print("start in loop");
        print('doc.id == ${doc.id}');
        notesFromFirestore.add(ProductModel.fromDocumentSnapshot(doc:doc));
        // print(ProductModel.fromDocumentSnapshot(doc:doc));
      }
      // print(notesFromFirestore.first.id.toString());
      return notesFromFirestore;});
    // int count = await allData.length;
    // print(aa.length);
    print( 'List Size = ${notesFromFirestore.length}');
    var count = 0;
    for (final ProductModel notesFromFirestoreA in notesFromFirestore) {
      count  ;
      print('Loop Counter == ${count}');
      print('Id == ${notesFromFirestoreA.id}');
      print('Name == ${notesFromFirestoreA.name}');
      print('Price == ${notesFromFirestoreA.price}');
      print('Brand == ${notesFromFirestoreA.brand}');
      print('image == ${notesFromFirestoreA.image}');
    }
  }

Source Code : executing function

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Record'),
        leading: null,
        actions: <Widget>[
          IconButton(
            icon: const Icon(Icons.add),
            onPressed: (){
              Navigator.pushNamed(context, creationCategory.id);
            },
          ),
          IconButton(
            icon: const Icon(Icons.settings),
            onPressed: () async {
              // await getData();
              getMessagesTestTest();
              // Navigator.push(
              //   context,
              //   MaterialPageRoute(builder: (context) => const ItemDetailsScrrent()),
              // );
            },
          ),
        ],
      ),
      body: SafeArea(
        child: Container(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[

              Text('Trahs Collection',
              style: const TextStyle(
                color: Colors.black38, fontWeight: FontWeight.bold, fontSize: 40),
              ),
              ItemStream(),
            ],
          ),
          ),
      ),
      );

  }

Source Code : class ProductModel

class ProductModel {
  static const ID = "id";
  static const IMAGE = "image";
  static const NAME = "name";
  static const BRAND = "brand";
  static const PRICE = "price";

  String? id;
  String? image;
  String? name;
  String? brand;
  int? price;

  ProductModel(
      {required this.id,
        required this.image,
        required this.name,
        required this.brand,
        required this.price});

  factory ProductModel.fromFire(QueryDocumentSnapshot snapshot) {
    return ProductModel.fromMap(snapshot as Map<String, dynamic>);
  }
  factory ProductModel.fromDocumentSnapshot({required DocumentSnapshot<Map<String,dynamic>> doc}){
    // print(doc.data()!["id"]);
    // print(doc.data()!["image"]);
    // print(doc.data()!["name"]);
    // print(doc.data()!["brand"]);
    // print(doc.data()!["price"]);
    return ProductModel(
      id: doc.data()!["id"],
      image: doc.data()!["image"],
      name: doc.data()!["name"],
      brand: doc.data()!["brand"],
      price: doc.data()!["price"],
    );
  }

  Map<String, dynamic> toJson() => {
    'id': id,
    'image': image,
    'name': name,
    'brand': brand,
    'price': price,
  };

  ProductModel.fromMap(Map<String, dynamic> data) {
    id = data[ID];
    image = data[IMAGE];
    name = data[NAME];
    brand = data[BRAND];
    price = data[PRICE];
  }
}

CodePudding user response:

Try to use log('your message') instead.

Do not forget the import:

import 'dart:developer';

CodePudding user response:

What offical document says .map is

Transforms each element of this stream into a new stream event.

So you have to listen "aa" variable witch is "Stream" to start listening data. like:

aa.listen(
  (event) => print("Data Retrieved"),
);
  • Related