-3

When I try to take a object in my home page I don't get an error, but even if I use the same method in the next screen to display my object from the database, FutureBuilder can't take any value.

@override
  Widget build(BuildContext context) {
    return WillPopScope(
      child: SafeArea(
        child: Scaffold(
          backgroundColor: kColorTheme1,
          appBar: AppBar(
            centerTitle: true,
            automaticallyImplyLeading: false,
            elevation: 20,
            backgroundColor: Color(0xFFF2C3D4).withOpacity(1),
            title:TitleBorderedText(title:"Sevimli Yemekler", textColor: Color(0xFFFFFB00)),
            actions: [
              CircleAvatar(
                radius: 27,
                backgroundColor: Colors.transparent,
                backgroundImage: AssetImage(kCuttedLogoPath),
              ),
            ],
          ),
          body: FutureBuilder<Map>(
            future: HiveHelper().getCategoryModels(),
            builder: (BuildContext context,AsyncSnapshot<Map> snapshot){
              if(snapshot.hasData) {
                _list = snapshot.data.values.toList();
              }
              Future.delayed(Duration(milliseconds: 200));
              return Container(
                decoration: BoxDecoration(
                  image: DecorationImage(
                    image: AssetImage(kBGWithLogoOpacity),
                    fit: BoxFit.cover,
                  ),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    Expanded(
                      child:GridView.builder(
                          scrollDirection: Axis.vertical,
                          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
                          itemCount: _list.length+1,
                          itemBuilder: (context,index){
                            if(_list.length==0){
                              return EmptyCard(where: "homeScreen",);
                            }
                            if(_flag==1){
                              return EmptyCard(where: "homeScreen",);
                            }
                            if(index==_list.length-1){
                              _flag=1;
                              CategoryModel categoryModel = _list[index];
                              return CategoryCard(category: categoryModel);
                            }
                            else{
                              CategoryModel categoryModel =_list[index];
                              return CategoryCard(category: categoryModel);
                            }
                          }
                      ),
                    ),
                    Column(
                      mainAxisAlignment: MainAxisAlignment.end,
                      crossAxisAlignment: CrossAxisAlignment.stretch,
                      children: [
                        Padding(
                          padding: EdgeInsets.all(10),
                          child: Container(
                            decoration: BoxDecoration(
                              border: Border.all(style: BorderStyle.solid),
                              color: kColorTheme7,
                              borderRadius: BorderRadius.circular(40),
                            ),
                            child: TextButton(
                                onPressed: (){
                                  showModalBottomSheet(
                                    isDismissible: false,
                                    enableDrag: false,
                                    context: context,
                                    builder: (BuildContext context)=> AddMenuScreen(buttonText: "Menü Ekle",route: "homeScreen",),
                                  );
                                },
                                child: TitleBorderedText(title: "LEZZET GRUBU EKLE",textColor: Colors.white,)
                            ),
                          ),
                        ),
                      ],
                    )
                  ],
                ),
              );
            },
          ),
        ),
      ),
      onWillPop: ()async{
        var response = await showAlertDialog(context);
        print(response);
        return response;
      },
    );
  }

I can display my object here without any error. I use the same database and same builder below, but I can take a value.

@override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        body: FutureBuilder<Map>(
          future: HiveHelper().getCategoryModel(widget.categoryId),
          builder: (BuildContext context,AsyncSnapshot<Map> snapshot) {
            if(snapshot.hasData) {
              _list=snapshot.data.values.toList();
            }
            Future.delayed(Duration(milliseconds: 200));
            return  Scaffold(
              appBar: AppBar(
                automaticallyImplyLeading: false,
                centerTitle: true,
                title: BorderedText(
                  child:Text(
                    _list[4],
                    style: TextStyle(
                        color: Color(0XFFFFFB00),
                        fontSize: 30,
                        fontFamily: "OpenSans"
                    ),
                  ),
                  strokeWidth: 5,
                  strokeColor: Colors.black,
                ),
                elevation: 5,
                backgroundColor: Color(0xFFF2C3D4).withOpacity(1),
                leading: IconButton(
                  icon: Icon(Icons.arrow_back),
                  onPressed: (){
                    Navigator.pop(context);
                  },
                  iconSize: 40,
                  color: Color(0xFFA2000B),
                ),
                actions: [
                  CircleAvatar(
                    radius: 27,
                    backgroundColor: Colors.transparent,
                    backgroundImage: AssetImage("images/cuttedlogo.PNG"),
                  )
                ],
              ),
              body:Container(
                decoration: BoxDecoration(
                  image: DecorationImage(
                    image: AssetImage("images/logoBGopacity.png"),
                    fit: BoxFit.cover,
                  ),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    Expanded(
                      child: GridView.builder(
                          scrollDirection: Axis.vertical,
                          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
                          itemCount:_list[5].length+1,
                          itemBuilder: (context,index){
                            if(_list[5].length==0){
                              return EmptyCard(where: "subCategoryScreen",categoryId: widget.categoryId,);
                            }
                            if(_flag==1){
                              return EmptyCard(where: "homeScreen",);
                            }
                            if(index==_list[5].length-1){
                              _flag=1;
                              SubCategoryModel subCategoryModel =SubCategoryModel();
                              return SubCategoryCard(subCategoryCardId:index,subCategoryId:subCategoryModel.subCategoryId,subcategoryName: subCategoryModel.subCategoryName,
                                subCategoryImagePath:subCategoryModel.subCategoryImagePath,
                                subCategoryCardColor: subCategoryModel.categoryColor,);
                            }
                            else{
                              SubCategoryModel subCategoryModel =SubCategoryModel();
                              return SubCategoryCard(subCategoryCardId:index,subCategoryId:subCategoryModel.subCategoryId,subcategoryName: subCategoryModel.subCategoryName,
                                subCategoryImagePath:subCategoryModel.subCategoryImagePath,
                                subCategoryCardColor: subCategoryModel.categoryColor,);
                            }
                          }
                      ),
                    ),
                    Column(
                      mainAxisAlignment: MainAxisAlignment.end,
                      crossAxisAlignment: CrossAxisAlignment.stretch,
                      children: [
                        Padding(
                          padding: EdgeInsets.all(10),
                          child: Container(
                            decoration: BoxDecoration(
                              border: Border.all(style: BorderStyle.solid),
                              color: kColorTheme7,
                              borderRadius: BorderRadius.circular(40),
                            ),
                            child: TextButton(
                              onPressed: (){
                                showModalBottomSheet(
                                  isDismissible: false,
                                  enableDrag: false,
                                  context: context,
                                  builder: (BuildContext context)=> AddMenuScreen(categoryId:widget.categoryId,buttonText: "Tarif Ekle", route:"subCategoryScreen"),
                                );
                              },
                              child: BorderedText(
                                strokeWidth: 5,
                                strokeColor: Colors.black,
                                child:Text("Tarif Ekle",style: TextStyle(
                                  color: Colors.white,
                                  fontFamily:'OpenSans',
                                  fontSize:30,
                                ),
                              ),
                            ),
                          ),
                        ),
                      ),
                    ],
                  )
                ],
              ),
            ),
          );
          }
        ),
      ),
    );
  }
class HiveHelper{

  void addCategoryModel(CategoryModel categoryModel)async{
    var box = await Hive.openBox('categoryModelsInBox');
    await box.add(categoryModel);
    await Hive.close();
  }
  Future <Map> getCategoryModels()async{
    var box = await Hive.openBox('categoryModelsInBox');
    var boxToMap=box.toMap();
    return boxToMap;
  }

  Future <Map> getCategoryModel(int index) async {
    var box = await Hive.openBox('categoryModelsInBox');
    var boxToMap=box.toMap();
    return boxToMap[index];
  }

  void addSubCategory(SubCategoryModel subCategoryModel, key)async{
    var box = await Hive.openBox('categoryModelsInBox');
    box.put(subCategoryModel,key);
  }
}

Here is my hive class. How can I fix this problem?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ygzkrmtc
  • 97
  • 7

2 Answers2

-1

I am not sure, but you could try:

Future <Map> getCategoryModel(int index) async {
    var box = await Hive.openBox('categoryModelsInBox');
    var boxToMap=box.toMap();
    return boxToMap["$index"];
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sam Chan
  • 1,665
  • 4
  • 14
-1

Don't create the future in the "future:" parameter of a FutureBuilder. As the first large paragraphs of the Fine Manual says:

The future must have been obtained earlier, e.g. during State.initState, State.didUpdateWidget, or State.didChangeDependencies. It must not be created during the State.build or StatelessWidget.build method call when constructing the FutureBuilder. If the future is created at the same time as the FutureBuilder, then every time the FutureBuilder's parent is rebuilt, the asynchronous task will be restarted.

A general guideline is to assume that every build method could get called every frame, and to treat omitted calls as an optimization.

https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html

Randal Schwartz
  • 39,428
  • 4
  • 43
  • 70