Provider 中的收藏夹列表问题 - 图标在 Flutter 中更改颜色

Problem in Provider with favorite list - icon changing color in Flutter

提问人:Badriya Haddad 提问时间:10/31/2022 更新时间:10/31/2022 访问量:206

问:

我正在使用具有收藏夹列表的提供程序。 所以这个想法是一个 Listview 包含从 Json 获取的数据,它们中的每一个都在 Listile 中,标题 whish 具有主要数据(字符串)和前导,其中包含字符串的 id 和尾随,应该具有最喜欢的图标,当它点击时将颜色变为红色,但事实证明这是一个问题,因为当我只点击一个时,它们也会发生变化,但很短的时间和颜色分散,所以这是第一个问题 第二个问题是与提供者有关! 如下图所示,当我点击列表图标时,它应该点击一个图标,它会显示显示收藏夹列表的屏幕,但它不会,而是显示(“食物”的实例),但根据我选项卡上的项目 所以这是主屏幕代码:

import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/container.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:note/Designs/Favorite_List.dart';
import 'package:note/Models/Favorite_List_Provider.dart';
import 'package:note/Models/Food_Models.dart';
import 'package:provider/provider.dart';

import '../Services/Fetch_Data.dart';
import 'Details_DesignOfDesignOne.dart';

class DesignOne extends StatefulWidget {
  const DesignOne({super.key, required this.Image, required this.Desc});
  final String Image;
  final String Desc;
  @override
  State<DesignOne> createState() => _DesignOneState();
}

class _DesignOneState extends State<DesignOne> {
  late Future<Food> futureFood;
  @override
  void initState() {
    super.initState();
    futureFood = fetchData(widget.Image, widget.Desc);
  }

  @override
  Widget build(BuildContext context) {
    bool ischecked = false;
    final provider = favorite.of(context);
    return Scaffold(
      backgroundColor: Colors.grey.shade200,
      appBar: AppBar(
        title: Text('Design one'),
        actions: [
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: InkWell(
              onTap: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => FavoriteScreen(Desc: '', Image: ''),
                  ),
                );
              },
              child: Icon(
                Icons.list,
                size: 30,
              ),
            ),
          )
        ],
      ),
      body: Consumer<favorite>(
          builder: (BuildContext context, favorite value, child) {
        return Center(
          child: FutureBuilder<Food>(
            future: fetchData(widget.Image, widget.Desc),
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return ListView.builder(
                    shrinkWrap: true,
                    itemCount: snapshot.data!.categories.length,
                    itemBuilder: (contxt, index) {
                      final fav = snapshot.data!;
                      return InkWell(
                        onTap: () {
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder: (context) => DetailsDo(
                                Desc: snapshot.data!.categories[index]
                                    .strCategoryDescription,
                                Image: snapshot
                                    .data!.categories[index].strCategoryThumb,
                              ),
                            ),
                          );
                        },
                        child: Card(
                          elevation: 2,
                          shape: RoundedRectangleBorder(
                            side: BorderSide(color: Colors.white70, width: 1),
                            borderRadius: BorderRadius.circular(50),
                          ),
                          child: ListTile(
                            title: Text(
                              snapshot.data!.categories[index].strCategory
                                  .toString(),
                              style: GoogleFonts.montserrat(
                                fontSize: 20,
                                fontWeight: FontWeight.w600,
                                fontStyle: FontStyle.italic,
                              ),
                            ),
                            leading: CircleAvatar(
                              backgroundColor:
                                  Color.fromARGB(213, 255, 251, 251),
                              child: Text(
                                snapshot.data!.categories[index].idCategory
                                    .toString(),
                                style: GoogleFonts.montserrat(
                                    fontSize: 20,
                                    fontWeight: FontWeight.w600,
                                    fontStyle: FontStyle.italic,
                                    color: Color.fromARGB(255, 148, 148, 135)),
                              ),
                            ),
                            trailing: IconButton(
                              icon: (provider.isExist(fav))
                                  ? const Icon(Icons.favorite,
                                      color: Colors.red)
                                  : const Icon(Icons.favorite_border),
                              onPressed: () {
                                provider.toggleFavorite(fav);
                              },
                            ),
                          ),
                        ),
                      );
                    });
              } else if (snapshot.hasError) {
                return Text('${snapshot.error}');
              }
              return const CircularProgressIndicator();
            },
          ),
        );
      }),
    );
  }
}

这是应该显示收藏夹项目的收藏夹列表屏幕:

import 'dart:ui';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:note/Models/Favorite_List_Provider.dart';
import 'package:provider/provider.dart';

import '../Models/Food_Models.dart';
import '../Services/Fetch_Data.dart';

class FavoriteScreen extends StatefulWidget {
  const FavoriteScreen({super.key, required this.Image, required this.Desc});
  final String Image;
  final String Desc;

  @override
  State<FavoriteScreen> createState() => _FavoriteScreenState();
}

class _FavoriteScreenState extends State<FavoriteScreen> {
  @override
  Widget build(BuildContext context) {
    final provider = favorite.of(context);
    final favr = provider.favoriteList;
    return Scaffold(
        appBar: AppBar(
          title: Text("Favorites"),
          centerTitle: true,
        ),
        body: Consumer<favorite>(
          builder: (context, favorite value, child) {
            return FutureBuilder<Food>(
                future: fetchData(widget.Image, widget.Desc),
                builder: (context, snapshot) {
                  if (snapshot.hasData) {
                    return ListView.builder(
                        shrinkWrap: true,
                        itemCount: favr.length,
                        itemBuilder: (context, index) {
                          final fav = favr;
                          return ListView(shrinkWrap: true, children: [
                            ListTile(
                              title: Text(fav[index].toString()),
                            ),
                          ]);
                        });
                  }
                  return const CircularProgressIndicator();
                });
          },
        ));
  }
}

那就是提供者:

import 'Food_Models.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class favorite extends ChangeNotifier {
  List<Food> _favoriteList = [];
  List<Food> get favoriteList => _favoriteList;

  void toggleFavorite(Food fav) {
    final isExist = _favoriteList.contains(fav);
    if (isExist) {
      _favoriteList.remove(fav);
    } else {
      _favoriteList.add(fav);
    }
    notifyListeners();
  }

  bool isExist(Food fav) {
    final isExist = _favoriteList.contains(fav);
    return isExist;
  }

  void clearFavorite() {
    _favoriteList = [];
    notifyListeners();
  }

  static favorite of(
    BuildContext context, {
    bool listen = true,
  }) {
    return Provider.of<favorite>(
      context,
      listen: listen,
    );
  }
}

所以这就是它向我展示的:the problem

Flutter 提供者 收藏夹

评论

0赞 Sanketh B. K 10/31/2022
发布与 prover.toggleFavorite 相关的代码
0赞 Badriya Haddad 10/31/2022
void toggleFavorite(Food fav) { final isExist = _favoriteList.contains(fav); if (isExist) { _favoriteList.remove(fav); } else { _favoriteList.add(fav); } notifyListeners();

答:

0赞 pmatatias 10/31/2022 #1
  • 问题 1:您应该添加 1 个类别,而不是所有类别
final fav = snapshot.data!; // in this line, fav is ALL FOOD 
  return InkWell(
  ....

你声明的是所有类别。但是在你添加的:favFOODCard

snapshot.data!.categories[index] // this line: only 1 food category

溶液: 更改为 1 个类别:fav

final fav = snapshot.data!.categories[index];

在您的列表中应该是:

List<Your_favorite_category> _yourfavoriteCategoryList = [];
List<Your_favorite_category> get yourfavoriteCategoryList=> _favoriteList;


  void toggleFavorite(YourFoodCategory fav) {
    final isExist = yourfavoriteCategoryList.contains(fav);
    if (isExist) {
      yourfavoriteCategoryList.remove(fav);
    } else {
      yourfavoriteCategoryList.add(fav);
    }
    notifyListeners();
  }
  • 问题 2:您正在打印一个对象,这就是它显示的原因Instance of <Food>
Text(fav[index].toString()) // this is print an object of Food

溶液: 在您的收藏夹列表中,它应该是类别列表。不显示 Food 对象

Text(fav.your_categories_object[index].toString()) // this is print your category

评论

0赞 Badriya Haddad 10/31/2022
在问题 1 中:它在图标部分显示错误:
0赞 Badriya Haddad 10/31/2022
尾随: IconButton( icon: (provider.isExist(fav)) ? const Icon(Icons.favorite, color: Colors.red) : const Icon(Icons.favorite_border), onPressed: () { provider.toggleFavorite(fav);
0赞 Badriya Haddad 10/31/2022
表示:不能将参数类型“Category”分配给参数类型“Food”。
0赞 pmatatias 10/31/2022
我不会确切地回答来解决您的问题。我上面的回答是让您的指南找到解决方案。
0赞 Badriya Haddad 10/31/2022
问题 2 仍然相同,实际上我已经尝试过了,但感谢您的帮助!:)