首页 > 解决方案 > 颤动的firebase数据库initState问题

问题描述

我的应用程序有一个具有属性 shopList 的对象公司。shoplist 将从 void initState() 中的 firebase 数据库获取数据。

Company(name: 'Storm',
      about: 'xxxxxxxxxxxx',
      backdropPhoto: 'assets/hk.jpg',
      shopList: [],
      location: 'HK',
      logo: 'assets/logo.png',
      president: 'Grand Production House');

shoplist 应该有 5 个不同的商店,但我不知道为什么会有 5 个数据相同的商店。

代码:

class CompanyDetailsPage extends StatefulWidget {

    CompanyDetailsPage(
      {@required AnimationController controller, this.context})
      : animation = new CompanyDetsIntroAnimation(controller);

  final BuildContext context;

  final CompanyDetsIntroAnimation animation;
  @override
  _CompanyDetailsPageState createState() => _CompanyDetailsPageState();
}

class _CompanyDetailsPageState extends State<CompanyDetailsPage> {

  Shop shopItems;

  Company storm = Company(
      name: 'Storm',
      about: 'xxxxxxxxxxxx',
      backdropPhoto: 'assets/hk.jpg',
      shopList: [],
      location: 'HK',
      logo: 'assets/logo.png',
      president: 'Grand Production House');

  DatabaseReference databaseReference = FirebaseDatabase.instance.reference();

  @override
  void initState() {
    super.initState();

    shopItems = Shop();

    databaseReference.child('HK').once().then((DataSnapshot snapshot) {
      Map uid = snapshot.value;
      uid.forEach((k,v) {
        Map shopMap = v['Shop'];

        shopMap.forEach((sk,sv) {
          shopItems.key = sk;
          shopItems.shopName = sv["ShopName"];
          shopItems.address = sv["ShopAddress"];
          shopItems.tel = sv["ShopTel"];
          shopItems.thumbnail = sv["Thumbnail"];


          debugPrint(shopItems.address);

          storm.shopList.add(shopItems);

          debugPrint(shopItems.key);
        });

      });

      for (int i = 0; i < storm.shopList.length; i++) {

        debugPrint("Username: ${storm.shopList[i].address }, User Id: ${storm.shopList[i].key}");

      }
    });
  }

在此处输入图像描述

来自控制台的结果:

标签: databasefirebaseflutter

解决方案


我认为问题可能出在您正在实例化的地方shopItems = Shop();

尝试从那里删除它并执行此操作

shopMap.forEach((sk,sv) {
//Create the instance here
  shopItems = Shop();

  shopItems.key = sk;
  shopItems.shopName = sv["ShopName"];
  shopItems.address = sv["ShopAddress"];
  shopItems.tel = sv["ShopTel"];
  shopItems.thumbnail = sv["Thumbnail"];


  debugPrint(shopItems.address);

  storm.shopList.add(shopItems);

  debugPrint(shopItems.key);
});

推荐阅读