【问题标题】:Flutter Add to Favorite Function from JSON DataFlutter 从 JSON 数据添加到收藏功能
【发布时间】:2021-03-24 17:54:51
【问题描述】:

我有一个 Json 列表,我在 ListView 的应用程序中获取该列表。在顶部,在应用程序栏中,我有一个 IconButton 导航到收藏页面。我有一个我的 Json listview 数据的详细页面,在详细页面中,我附加了一个 IconButton,它可以切换图标以使收藏和取消收藏列表数据。 updates_details.dart

class UpdateDetails extends StatefulWidget {
  final String detail;
  UpdateDetails({this.detail});

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

class _UpdateDetailsState extends State<UpdateDetails> {

  bool _isFavorited = true;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Updates',style: TextStyle(color: Colors.white),),
        elevation: 0,
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.only(
                bottomRight: Radius.circular(35),
                bottomLeft: Radius.circular(35)
            )
        ),
        actions: [
          IconButton(
            padding: EdgeInsets.symmetric(horizontal: 20,vertical: 5),
            alignment: Alignment.centerRight,
            icon: (_isFavorited ? Icon(Icons.favorite,size: 35,color: Colors.pink,) : Icon(Icons.favorite_border,size: 35,)),
            onPressed: _toggleFavorite,
          ),
        ],

      ),
      body: Container(
        padding: EdgeInsets.all(12.0),
        child:
        Html(
          data: this.widget.detail,
          style: {
            "html": Style(
              fontSize: FontSize.xLarge,
            ),
            'Strong': Style(color: Colors.blue)
          },
        ),
      ),
    );
  }
  void _toggleFavorite() {
    setState(() {
      if (_isFavorited) {
        _isFavorited = false;
      } else {
        _isFavorited = true;
      }
    });
  }
}

现在,当我单击 IconButton 时,它会从喜欢变为不喜欢。现在,请提供解决方案,在 shared_preferences 的帮助下将这些列表视图的详细信息页面保存为收藏或不收藏,我可以从我的收藏页面获取列表视图中所有收藏的项目。

这是我的 listItem 页面。最近的_updates.dart

class RecentUpdates extends StatefulWidget {
  @override
  _RecentUpdatesState createState() => _RecentUpdatesState();
}

class _RecentUpdatesState extends State<RecentUpdates> {

  List<RecentUpdate> _updateList = List<RecentUpdate>();
  RecentUpdateService _recentUpdateService = RecentUpdateService();
  bool isLoading = true;

  _getRecentUpdates() async {
    var updates = await _recentUpdateService.getRecentUpdates();
    var result = json.decode(updates.body);
    result['data'].forEach((data) {
      var model = RecentUpdate();
      model.id = data["id"];
      model.title = data["title"];
      model.details = data["details"];
      model.image = data["file"];
      setState(() {
        _updateList.add(model);
        isLoading = false;
      });
    });
  }
  @override
  void initState() {
    super.initState();
    _getRecentUpdates();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.only(
                bottomRight: Radius.circular(35),
                bottomLeft: Radius.circular(35)
            )
        ),
        title: Text('Recent Updates',style: TextStyle(color: Colors.white),),
        elevation: 0,
        actions: [
          IconButton(icon: Icon(Icons.favorite,size: 35,color: Colors.pink,), onPressed: (){
            Navigator.push(context, MaterialPageRoute(builder: (context)=>FavoritePage()));
          }),
          SizedBox(width: 10,)
        ],
      ),
      body: isLoading ? Center(
        child: CircularProgressIndicator(
          backgroundColor: Colors.deepPurple,
          strokeWidth: 10,
        ),
      )
          : ListView.builder(
        itemCount: _updateList.length,
        itemBuilder: (context, index){
          if(_updateList.length != 0){
            return Container(
              decoration: BoxDecoration(
                  border: Border.all(color: Colors.blueAccent)
              ),
              child: Padding(
                padding: const EdgeInsets.only(left: 5),
                child: Row(
                  children: [
                    FadeInImage(
                      placeholder: AssetImage('assets/images/kids.png'),
                        height: 110,width: 100,
                        image: NetworkImage(_updateList[index].image, )),
                    SizedBox(width: 5,),
                    Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Container(
                          width: 280,
                            child: Text(_updateList[index].title,maxLines: 2,style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),)),
                        FlatButton(
                          color: Colors.blue,
                            onPressed: (){
                            Navigator.push(context, MaterialPageRoute(builder: (context)=>UpdateDetails(
                              detail: _updateList[index].details
                            )));
                            },
                            child: Text("Read Details",style: TextStyle(fontSize: 20,color: Colors.white),))
                      ],
                    ),
                  ],
                ),
              ),
            );
          }
            return CircularProgressIndicator();
        },
      )
    );
  }
}

这是我的模型课 更新.dart

class RecentUpdate{
  int id;
  String image;
  String title;
  String details;
}

请给我建议和解决方案。谢谢

【问题讨论】:

    标签: flutter dart flutter-layout sharedpreferences flutter-dependencies


    【解决方案1】:

    您必须在 sharedPreferences 中以 json 格式存储最近更新对象

    所以首先你必须让你的模型可序列化:

    class RecentUpdate {
      final int id;
      final String image;
      final String title;
      final String details;
      RecentUpdate({
        required this.id,
        required this.image,
        required this.title,
        required this.details,
      });
    
      Map<String, dynamic> toMap() {
        return {
          'id': id,
          'image': image,
          'title': title,
          'details': details,
        };
      }
    
      factory RecentUpdate.fromMap(Map<String, dynamic> map) {
        return RecentUpdate(
          id: map['id'],
          image: map['image'],
          title: map['title'],
          details: map['details'],
        );
      }
    
      String toJson() => json.encode(toMap());
    
      factory RecentUpdate.fromJson(String source) =>
          RecentUpdate.fromMap(json.decode(source));
    }
    
    

    那你需要三个函数,我自己写个psudo代码自己调试吧

    void save(RecentUpdate r) async {
      final prefs = await SharedPreferences.getInstance();
      List rups = [];
      if (prefs.getString("fave") != null)
        rups = json.decode(prefs.getString("fave"));
      rups.add(r.toMap()); 
      prefs.setString("fave", json.encode(rups));
    }
    
    void delete(RecentUpdate r)async {
      final prefs = await SharedPreferences.getInstance();
      List rups = [];
      if (prefs.getString("fave") != null)
        rups = json.decode(prefs.getString("fave"));
      rups.remove(r);
      prefs.setString("fave", json.encode(rups));
    }
    
    Future<List<RecentUpdate> read() async{
      final prefs = await SharedPreferences.getInstance();
      List rups json.decode(prefs.getString("fave"));
      return rups;
    }
    

    这也可能有助于https://betterprogramming.pub/flutter-how-to-save-objects-in-sharedpreferences-b7880d0ee2e4

    【讨论】:

    • 请告诉我工厂RecentUpdate.fromJson(String source) => RecentUpdate.fromMap(json.decode(source));
    • 请给我完整的例子。
    【解决方案2】:

    当您在列表页面上时,您应该为每个项目都有一个收藏图标,而不是在应用栏中。

    【讨论】:

    • 其实这是一个导航收藏页面的按钮,我想从列表详细信息页面中进行收藏
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-22
    • 1970-01-01
    相关资源
    最近更新 更多