如何在蜂巢扑动中创建一个最喜欢的按钮?

How to create a favorite buton in hive flutter?

我正在尝试为我的应用创建收藏按钮。哪个工作是改变和保存颜色,而用户按下它,所以我决定使用hive db来做。点击图标按钮时;颜色发生变化,向用户表明它已被标记为他们的最爱。问题是当我再次点击它时(如果用户想取消标记)虽然颜色改变了,当我移动到其他页面或热 start/reload 页面时,颜色自动变回原来的颜色(To第一次按下时的颜色)。我希望颜色通过按钮反应并保存。怎么解决这个问题?(我在关键部分有点迷糊,可能就是问题所在)

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

     class _p1State extends State<p1> {
     Box box;
     bool _isFavorite = false;

     _p1State();
     @override
     void initstate(){
     super.initState();
    // Get reference to an already opened box

     box = Hive.box(FAVORITES_BOX);
     final data = box.get(_isFavorite).containskey("1" != null ? Colors.white:Colors.red );
    }

    @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('      "\n           The  entire  world ,       \n                is  not  worth \n                     A  single  Tear.\n'
                  '                                                      " \n                -Imam Hazrat Ali (R) '
                  ,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;
                      });
                      if(box.containsKey(1)){
                        box.delete(1);
                      }else
                      box.put(1, _isFavorite);



                    }

                )
            )
        )])

      ),
    );
  }
}

你可以直接初始化已经打开的hive

  Box box = Hive.box(FAVORITES_BOX);
  bool _isFavorite = false;

  @override
  void initState() {
    super.initState();
    _isFavorite = box.get(0) ?? false;
  }

并更改值

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

  box.put(0, _isFavorite);
},

我看到你在使用 bool _isFavorite 来记录一个赞,然后你再次检查 is favorite 的值以了解是给予赞还是移除赞,在幕后你的蜂巢正在工作,但基本上,你用来更新颜色的代码不是来自蜂巢,所以当你重新更新你的状态时,例如热重载,一切都重置为初始状态,你最喜欢的按钮保持不变。

您基本上只需要重新建模您的逻辑即可使其正常工作。

import 'package:hive_flutter/hive_flutter.dart';

void main() async {
  await Hive.initFlutter();
  await Hive.openBox("favorites");
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  Box? box = Hive.box("favorites");
  bool _isFavorite = false;
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Stack(
          children: <Widget>[
            Align(
              alignment: Alignment.center,
              child: Text(
                '      "\n           The  entire  world ,       \n                is  not  worth \n                     A  single  Tear.\n'
                '                                                      " \n                -Imam Hazrat Ali (R) ',
                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: box!.isEmpty ? Colors.white : Colors.red),
                onPressed: () {
                  setState(() {
                    _isFavorite = !_isFavorite;
                  });
                  if (box!.isEmpty)
                    box!.put("isFavorite", _isFavorite);
                  else
                    box!.delete("isFavorite");
                },
              )),
            )
          ],
        ),
      ),
    );
  }
}