如何将收藏夹按钮添加到详细信息,以将其保存并显示在flutter应用程序的“收藏夹”页面中

时间:2020-07-18 14:57:04

标签: flutter flutter-layout flutter-dependencies flutter-test

我的应用程序中有一个带有元素的GridView,每个元素都有其自己的详细信息,我想在每个详细信息页面中添加收藏夹按钮。 但我想在本地永久执行此操作,以便退出该应用程序后的用户下次可以找到它。 (我正在寻找一个清晰的示例或简单示例)

1 个答案:

答案 0 :(得分:0)

您可以在应用程序中使用“共享首选项”插件,并将bool值存储为收藏夹。如果为null或false,则将其显示为“收藏夹”;如果为true,则将其显示为收藏夹。

将此添加到您程序包的pubspec.yaml文件中:

依赖关系: shared_preferences:^ 0.5.8 然后在您的dart文件中导入“ package:shared_preferences / shared_preferences.dart”并使用此代码。

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

class _MyHomePageState extends State<MyHomePage> {
  List<Objects> _listData; //instead of this use your data here;
  bool _favStatus=false; // status to show favorite or not
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        height: MediaQuery.of(context).size.height,
        width: MediaQuery.of(context).size.width,
        child: GridView.builder(itemCount: _listData.length,
          gridDelegate:
              SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3),
          itemBuilder: (context, index) {
            checkFavStatus( _listData[index].name);
                        return Container(height: 100, width: 100,
                        child:IconButton(icon: Icon(Icons.favorite,color:_favStatus?Colors.red:Colors.black),
                         onPressed: (){setFav(_listData[index].name,_favStatus);},
                         ),
                       );
                      },
                    ),
                  ),
                );
              }
            
              void checkFavStatus(String name)async {
                 SharedPreferences prefs = await SharedPreferences.getInstance();
                 var boolValue = prefs.getBool(name);
                 if(boolValue==null||boolValue==false){
                   _favStatus=false;
                 }
                 else{
                   _favStatus=true;
                 }
              }

              void setFav(String name,bool _currentFavStatus){
                SharedPreferences prefs = await SharedPreferences.getInstance();
                prefs.setBool(name,!_currentFavStatus);
                setState(() {
                  
                });
              }
}