【问题标题】:How to added a favorites button to details that will save and display them in favorites page in a flutter App如何将收藏夹按钮添加到将保存并显示在颤振应用程序的收藏夹页面中的详细信息
【发布时间】:2020-11-08 04:56:33
【问题描述】:

我的应用程序中有一个带有元素的 GridView,每个元素都有自己的详细信息,我想在每个详细信息页面中添加收藏按钮。 但我想在本地和永久地这样做,以便用户在退出应用程序后会找到下一次。 (我正在寻找一个清晰的例子或一个简单的)

【问题讨论】:

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


    【解决方案1】:

    您可以在您的应用中使用共享首选项插件并将布尔值存储为收藏。如果为 null 或 false,则显示为不喜欢,如果为 true,则显示为喜欢。

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

    依赖: 共享首选项:^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(() {
                      
                    });
                  }
    }
    
    

    【讨论】:

    • 感谢您的回复,我试图重现它并用我的数据替换它,但在 getBool 中我收到此错误“方法 'getBool' 没有为类型 'Future' 定义。尝试纠正……”?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多