flutter firebase database and ListView builder issue

8,694

Try this.

That's what I would do

Shop.dart

class Shop {
  String key;
  String name;
  String address;
  String phone;
  String thumbnail;

  Shop(this.name,this.address,this.phone,this.thumbnail);

  Shop.fromSnapshot(DataSnapshot snapshot)
      : key = snapshot.key,
        name = snapshot.value["name"],
        address= snapshot.value["address"],
        phone= snapshot.value["phone"],
        thumbnail= snapshot.value["thumbnail"];


  toJson() {
    return {
      "name": name,
      "address": address,
      "phone": phone,
      "thumbnail": thumbnail,
    };
  }
}

main.dart

List<Shop> itemsShop = List();
Shop itemShop;
DatabaseReference itemRefShop;

@override
void initState() {
  super.initState();
  itemShop = Shop("", "", "", "");
  final FirebaseDatabase database = FirebaseDatabase.instance;
  itemRefShop = database.reference().child('Shop');
  itemRefShop.onChildAdded.listen(_onEntryAddedShop);
  itemRefShop.onChildChanged.listen(_onEntryChangedShop);
}

_onEntryAddedShop(Event event) {
  setState(() {
    itemsShop.add(Shop.fromSnapshot(event.snapshot));
  });
}

_onEntryChangedShop(Event event) {
  var old = itemsShop.singleWhere((entry) {
      return entry.key == event.snapshot.key;
  });
  setState(() {
      itemsShop[Shop.indexOf(old)] = Shop.fromSnapshot(event.snapshot);
  });
}

 @override
  Widget build(BuildContext context) {
     return new Container(
        child: new Column(
          children: <Widget>[
             new Flexible(
              child: new FirebaseAnimatedList(
                     query: itemRefShop,
                     itemBuilder:(_, DataSnapshot snapshot, Animation<double> animation, int index){
                       return new ListTile(
                         title: new Text(snapshot.value['name']),
                         subtitle: new Text(itemsShop[index].address),
                       );
                     }
               ),
          ]
        ),
     );
  }
}
Share:
8,694
GPH
Author by

GPH

Updated on November 30, 2022

Comments

  • GPH
    GPH over 1 year

    I suppose to show each item of my shopList in ListView, but I can't find out the reason why it keep showing the same record. Please help to solve this issue.

    Here with the code, get data from firebase database.

     databaseReference.once().then((DataSnapshot snapshot) {
        Map<dynamic, dynamic> getMap = snapshot.value;
        getMap.forEach((k, v) {
    
          Map<dynamic, dynamic> f = v;
          shop.key = k;
      shop.shopName = f["ShopName"];
      shop.tel = f["ShopTel"];
      shop.address = f["ShopAddress"];
      shop.thumbnail = f["Thumbnail"];
      debugPrint(k);
    
      shopList.add(shop);
      debugPrint(shopList[shopList.length-1].shopName);
    
    
    });
      });
    

    DebugPrint result:

    • flutter: -LLySYDHHHx9WtCvKPrO
    • flutter: shop1111
    • flutter: -LLyXwR0nnAcx6_H4cYy
    • flutter: shop2222

    Here with the database: enter image description here

    Here with the code for ListView:

    child: Flexible(
                    child: new ListView.builder(
                        itemCount: shopList.length,
                        itemBuilder: (context, index) {
                          return new Card(
                            color: Colors.red,
                            //elevation: 2.0,
                            child: new ListTile(
    
                              title: new Text("Name: ${shopList[index].key}"),
    
                            ),
                          );
    
    
                        }),
                ),
    

    the result of simulator:

    enter image description here

    • DomingoMG
      DomingoMG over 5 years
      Why not use Firebase Animated List? Do you have an object called shop?
  • GPH
    GPH over 5 years
    thanks, May I know how and when to terminate the firebase listener?
  • DomingoMG
    DomingoMG over 5 years
    The _onEntryChangedShop events tell you the event that has changed, and the _onEntryAddedShop the event that they are added. You can use print(event.snapshot.value); inside each listening
  • GPH
    GPH over 5 years
    for swift and kotlin, we have to stop the listener. Shall we stop the listener somewhere?
  • DomingoMG
    DomingoMG over 5 years