2021-12-09

Tech Programing

程式人小天地

Why my Favorite button made using hive Database aint working?

1 min read


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

                }

            )
        )
     )])

   ),
  );
}

}



Source link

資料來源:Stackoverflow

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *