Home > Mobile >  Why my Favorite button made using hive Database aint working?
Why my Favorite button made using hive Database aint working?

Time:12-09

I am trying to create a favorite button for my app. Which work is to change and save color, while the user press it, So I decided to use hive db for it. The problem is, when i tap on the button; the color get changed, but when i move to other page or hot start/reload the page, the color changed back to it former self automatically.How to solve this problem and create a favorite button successfully.

 class p1 extends StatefulWidget {
 @override
 _p1State createState() => _p1State();
 }

class _p1State extends State<p1> {
Box box;

_p1State();
@override
void initstate(){
super.initState();
// Get reference to an already opened box
box = Hive.box(FAVORITES_BOX);
}
@override
void dispose() {
// Closes all Hive boxes
Hive.close();
super.dispose();
}
get_info(){
var info = box.get(_isFavorite);
}

var _isFavorite = true;
@override
Widget build(BuildContext context) {
return MaterialApp(
  home: Scaffold(
   body:Stack(
       children:<Widget>[
       Image(
       image:AssetImage("Image/Chowsun1.jpg"),
     fit:BoxFit.cover,
     width: double.infinity,
     height: double.infinity,
   ),
      Align(alignment: Alignment.center,
          child: Text(' Rehman   '
              ,style: TextStyle(fontSize: 35.0,
                  color: Colors.white,
                  fontFamily: "Explora",
                  fontWeight: FontWeight.w900 ) )



      ),
         Stack ( children: [Positioned(
           top:90,
           right: 20,
           child:const Text('   1 ',
              style: TextStyle(
                 fontSize: 25.0,
                 color: Colors.white,
                 fontFamily: "Comforter"
             ),
           ),
         )], ),





    Align(
        alignment: Alignment.bottomCenter,
        child: (
            IconButton(
                icon: Icon(
                  Icons.favorite,
                    color:_isFavorite ? Colors.white: Colors.red


                ),
                onPressed: () {

                  setState(() {
                    _isFavorite= !_isFavorite;
                  });

                  box.put(!_isFavorite, _isFavorite);
                  get_info();

                }

            )
        )
     )])

   ),
  );
}

}

CodePudding user response:

There are a lot of things that don't make sense in this code.

I believe that the flow should be like this.

  • Your Widget first initialize the hive box and check if there is any data to refer to.
  • If there is a data already written, load it, or else, set a default value, which I bet is false. Because everything is not favorite before you make it so.
  • When you click Favorite button, it updates _isFavorite value and put it in the open Box with a key which must be a unique value that can represent the selected item right

There are problems in your code:

  • You initialized the Box in initState() but you didn't consider if there is data already in Box. So you have to check and if there is data you can use, you have to update _isFavorite accordingly.
  • You close Box every time your widget is disposed but I don't see your widget opens it again when you're back to the widget. So just don't close it. It seems like you'll use it very often.
  • You put the data with a key, which is the old data whose data type is boolean. It's binary so it can't be used as an unique key.

So if I were you, I would fix the code like following:

import 'package:flutter/material.dart';
import 'package:hive/hive.dart';

class p1 extends StatefulWidget {
  @override
  _p1State createState() => _p1State();
}

class _p1State extends State<p1> {
  late Box box;
  late bool _isFavorite;
  @override
  void initState() {
    super.initState();
    // Get reference to an already opened box.
    // This should be open before you re-enter this widget.
    box = Hive.box('FAVORITES_BOX');
    // Try getting data that already exists
    final data = box.get(someKeyYouAlreadyUsed);
    // if there is no data about favorite, assign false to _isFavorite
    _isFavorite = data ?? false;
  }


// Don't close the Hive Box if you're planning to come back and use it soon.
//   @override
//   void dispose() {
// // Closes all Hive boxes
//     Hive.close();
//     super.dispose();
//   }

  // I deleted this function. It doesn't do anything.
  // get_info() {
  //   var info = box.get(_isFavorite);
  // }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
          body: Stack(children: <Widget>[
        const Image(
          image: AssetImage("Image/Chowsun1.jpg"),
          fit: BoxFit.cover,
          width: double.infinity,
          height: double.infinity,
        ),
        const Align(
            alignment: Alignment.center,
            child: Text(' Rehman   ',
                style: TextStyle(
                    fontSize: 35.0,
                    color: Colors.white,
                    fontFamily: "Explora",
                    fontWeight: FontWeight.w900))),
        Stack(
          children: const [
            Positioned(
              top: 90,
              right: 20,
              child: Text(
                '   1 ',
                style: TextStyle(
                    fontSize: 25.0,
                    color: Colors.white,
                    fontFamily: "Comforter"),
              ),
            )
          ],
        ),
        Align(
            alignment: Alignment.bottomCenter,
            child: (IconButton(
                icon: Icon(Icons.favorite,
                    color: _isFavorite ? Colors.white : Colors.red),
                onPressed: () {
                  setState(() {
                    _isFavorite = !_isFavorite;
                  });
                  box.put(someUniqueValueToRepresentThisItem, _isFavorite);
                })))
      ])),
    );
  }
}


I hope this would work for you.

CodePudding user response:

You are setting the state of button on the basis of _isFavorite variable value instead of the value which came from the hive database (your get info function). After inserting the value in hive db you must set the state of button using hive db value instead of the _isFavorite variable.

  • Related