Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why my Favorite button made using hive Database aint working?

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();

                }

            )
        )
     )])

   ),
  );
}

}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading