flutter firebase数据库initState问题

问题描述 投票:0回答:1

我的应用程序有一个对象公司,它有一个属性shopList。商店列表将从void initState()中的firebase数据库中获取数据。

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

店铺应该有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}");

      }
    });
  }

enter image description here

控制台的结果:

  • 将文件同步到设备iPhone X ...
  • 颤振:-LM3JFMq5y9fNVA431QW
  • 扑:-LMHR9YQFqgKlnFArwEN
  • 颤振:-LM3JH8KMha3aeN-YEq5
  • 扑:-LM3JJTFda0c3qKaKEaL
  • 扑:-LMIaUIBOhj1k6pjj9eY
  • flutter:ShopAddress:bbbbbb,ShopKey:-LMIaUIBOhj1k6pjj9eY
  • flutter:ShopAddress:bbbbbb,ShopKey:-LMIaUIBOhj1k6pjj9eY
  • flutter:ShopAddress:bbbbbb,ShopKey:-LMIaUIBOhj1k6pjj9eY
  • flutter:ShopAddress:bbbbbb,ShopKey:-LMIaUIBOhj1k6pjj9eY
  • flutter:ShopAddress:bbbbbb,ShopKey:-LMIaUIBOhj1k6pjj9eY
database firebase flutter
1个回答
1
投票

我认为问题可能在于你实例化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);
});
© www.soinside.com 2019 - 2024. All rights reserved.