flutter - 每次都需要热加载flutter应用程序以便从Firebase实时数据库中获取数据

标签 flutter dart

这是我的代码:

class CategoryHomeScreen extends StatefulWidget {
  @override
  _CategoryHomeScreenState createState() => _CategoryHomeScreenState();
}

class _CategoryHomeScreenState extends State<CategoryHomeScreen> {

  List<CategoriesOnly> categoriesOnlyList =[];
  List<CategoryItems> categoryItemList = [];



@override
void initState() {
    // TODO: implement initState
    getCategoriesName();
    super.initState();

  }
  Future<void> getCategoriesName() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    var userPin = prefs.getString('pin');

    var CategoryName =  FirebaseDatabase.instance.reference().child('CategoryNames').child(userPin).once()
        .then((DataSnapshot dataSnapshot){
      var key  = dataSnapshot.value.keys;
      for(var i in key)
      {
       // print(dataSnapshot.value[i]['Name']);
        CategoriesOnly categoriesOnly = new CategoriesOnly(
            dataSnapshot.value[i]['Name']
        );
        categoriesOnlyList.add(categoriesOnly);
      }

    });

    var categoryItemDetails =  FirebaseDatabase.instance.reference().child('Categories').child(userPin).once()
        .then((DataSnapshot dataSnapshot){
      var key  = dataSnapshot.value.keys;
      for(var i in key)
      {
        CategoryItems categoryItems = new CategoryItems(
            dataSnapshot.value[i]['CategoryName'],
            dataSnapshot.value[i]['MarketPrice'],
            dataSnapshot.value[i]['Name'],
            dataSnapshot.value[i]['OurPrice'],
            dataSnapshot.value[i]['TotalDiscount'],
            dataSnapshot.value[i]['Weight']

        );
        categoryItemList.add(categoryItems);
      }

    });
  }

  @override
  Widget build(BuildContext context) {
    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
      statusBarColor: Colors.black, //or set color with: Color(0xFF0000FF)
    ));
    return Scaffold(
      backgroundColor: Colors.black,
      body: SafeArea(

        child:
        ListView.builder(
          itemCount: categoriesOnlyList.length,
          itemBuilder: (context, index1) =>
              Column(children: [
                Text(categoriesOnlyList[index1].Name,style: TextStyle(color:Colors.white),),
                Container(
                  height: 200,
                  decoration: BoxDecoration(borderRadius: BorderRadius.circular(8)),
                  child:
                  ListView.builder(itemCount: categoryItemList.length,
                      scrollDirection: Axis.horizontal,
                      itemBuilder: (context, index) {
                       return categoriesOnlyList[index1].Name == categoryItemList[index].CategoryName?
                         Padding(
                          padding: const EdgeInsets.all(8.0),
                          child: Container(
                            height: 200,
                            width: 200,
                            decoration: BoxDecoration(borderRadius: BorderRadius.circular(8)),
                            child: Card(
                              color: Colors.white,
                                child: Text(categoryItemList[index]
                                .Name,style: TextStyle(),overflow: TextOverflow.ellipsis,)),
                          ),
                        ):Container(
                       );
                      }),
                ),

              ]),
        )
      ),
    );
  }
}
这是我从Firebase实时数据库加载数据的应用程序。当我安装该应用程序时,它不会显示任何数据,但是当我重新加载(热重载)该应用程序时,它会显示所有数据,而当我退出该应用程序并再次启动它时,我将无法再次看到该数据。但是我希望我的页面显示一些加载小部件,直到它加载数据然后返回页面。或者使用数据简化页面。

最佳答案

可能是因为categoryItemList.length为0。
您可以使用调试器进行检查,或者在长度为0时显示一些内容。

class CategoryHomeScreen extends StatefulWidget {
  @override
  _CategoryHomeScreenState createState() => _CategoryHomeScreenState();
}

class _CategoryHomeScreenState extends State<CategoryHomeScreen> {
  List<CategoriesOnly> categoriesOnlyList = [];
  List<CategoryItems> categoryItemList = [];

  @override
  void initState() {
    // TODO: implement initState
    getCategoriesName();
    super.initState();
  }

  Future<void> getCategoriesName() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    var userPin = prefs.getString('pin');

    var CategoryName = FirebaseDatabase.instance
        .reference()
        .child('CategoryNames')
        .child(userPin)
        .once()
        .then((DataSnapshot dataSnapshot) {
      var key = dataSnapshot.value.keys;
      for (var i in key) {
        // print(dataSnapshot.value[i]['Name']);
        CategoriesOnly categoriesOnly =
            new CategoriesOnly(dataSnapshot.value[i]['Name']);
        categoriesOnlyList.add(categoriesOnly);
      }
    });

    var categoryItemDetails = FirebaseDatabase.instance
        .reference()
        .child('Categories')
        .child(userPin)
        .once()
        .then((DataSnapshot dataSnapshot) {
      var key = dataSnapshot.value.keys;
      for (var i in key) {
        CategoryItems categoryItems = new CategoryItems(
            dataSnapshot.value[i]['CategoryName'],
            dataSnapshot.value[i]['MarketPrice'],
            dataSnapshot.value[i]['Name'],
            dataSnapshot.value[i]['OurPrice'],
            dataSnapshot.value[i]['TotalDiscount'],
            dataSnapshot.value[i]['Weight']);
        categoryItemList.add(categoryItems);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    SystemChrome.setSystemUIOverlayStyle(
      SystemUiOverlayStyle(
      statusBarColor: Colors.black, //or set color with: Color(0xFF0000FF)
      ),
    );

    return Scaffold(
      backgroundColor: Colors.black,
      body: SafeArea(
        child: ListView.builder(
          itemCount: categoriesOnlyList.length, // place breakpoint here
          itemBuilder: (context, index1) {
            if (categoriesOnlyList == null || categoriesOnlyList.length == 0) {
              return CircularProgressIndicator(); // you should see loading animation if list is empty
            }

            return Column(
            children: [
              Text(
                categoriesOnlyList[index1].Name,
                style: TextStyle(color: Colors.white),
              ),
              Container(
                height: 200,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(8),
                ),
                child: ListView.builder(
                  itemCount: categoryItemList.length, // place breakpoint here
                  scrollDirection: Axis.horizontal,
                  itemBuilder: (context, index) {
                    if (categoryItemList == null || categoryItemList.length == 0) {
                      return CircularProgressIndicator(); // you should see loading animation if list is empty
                    }

                    return categoriesOnlyList[index1].Name ==
                            categoryItemList[index].CategoryName
                        ? Padding(
                            padding: const EdgeInsets.all(8.0),
                            child: Container(
                              height: 200,
                              width: 200,
                              decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(8)),
                              child: Card(
                                  color: Colors.white,
                                  child: Text(
                                    categoryItemList[index].Name,
                                    style: TextStyle(),
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                ),
                              ),
                            )
                        : Container();
                  },
                ),
              ),
            ],
          ),
          }
        ),
      ),
    );
  }
}

解决方案是使用FutureBuilder
警告:应用程序将多次运行build方法,这是将不希望被重复调用的任何内容(例如数据库调用或更改系统覆盖)放置在该方法之外的一种好习惯。
SystemChrome.setSystemUIOverlayStyle(
  SystemUiOverlayStyle(
    statusBarColor: Colors.black, // or set color with: Color(0xFF0000FF)
  ),
);

关于flutter - 每次都需要热加载flutter应用程序以便从Firebase实时数据库中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62502041/

相关文章:

android - Flutter:如何赋予彩色容器不透明度?

google-maps - 初始化问题。如何将类似这样的内容转换为静态成员?如果那是我需要做的

firebase - Flutter:Firebase 如何更改查询和内容

flutter - 行的子级不得包含任何空值 flutter 错误

flutter - 如何将特定索引处的值添加到 dart 中的空列表中?

dart - 如何在Dart编辑器中更改文件类型关联?

flutter - 在自定义小部件 flutter 中使函数参数可选

sql - 我该如何解决?Flutter sqflite删除不起作用

android - 类型 '_InternalLinkedHashMap<String, dynamic>'不是类型转换中类型 'Session'的子类型

dart - Flutter 的崩溃报告