Всем привет.
Пытаюсь сделать фичу добавления Item на экран Избранное через provider.
При нажатии на иконку, цвет меняется на зеленый, item добавляется и сохраняется на экране Избранное, НО через несколько секунд цвет иконки снова становится серый, как будто Item больше нет в Избранном, хотя он там.
Ниже код
void main() {
runApp(
OverlaySupport(
child: MultiProvider(
providers: [
ChangeNotifierProvider(create: (context) => ThemeProvider()),
ChangeNotifierProvider(create: (context) => AuthModel()),
ChangeNotifierProvider(create: (context) => SubscriptionStatusProvider()),
ChangeNotifierProvider(create: (context) => FavoritesProvider()),
],
child: Builder(
builder: (context) {
final favoritesProvider = Provider.of<FavoritesProvider>(context, listen: false);
favoritesProvider.loadFavorites();
return const APP();
},
),
),
),
);
}
class FavoritesProvider with ChangeNotifier {
List<Favoritable> _favorites = [];
List<Favoritable> get favorites => _favorites;
void addToFavorites(Favoritable item) {
_favorites.add(item);
_saveFavorites();
notifyListeners();
}
void removeFromFavorites(Favoritable item) {
_favorites.remove(item);
_saveFavorites();
notifyListeners();
}
bool isFavorite(Favoritable item) {
return _favorites.contains(item);
}
// Load favorites from shared preferences
Future<void> loadFavorites() async {
final prefs = await SharedPreferences.getInstance();
final favoritesJson = prefs.getString('favorites');
if (favoritesJson != null) {
final favoritesList = json.decode(favoritesJson) as List;
_favorites = favoritesList.map((item) => Favoritable.fromJson(item)).toList();
notifyListeners();
}
}
// Save favorites to shared preferences
Future<void> _saveFavorites() async {
final prefs = await SharedPreferences.getInstance();
final favoritesJson = json.encode(_favorites.map((item) => item.toJson()).toList());
await prefs.setString('favorites', favoritesJson);
}
}
class Screen extends StatefulWidget {
final DateTime selectedDate;
const Screen({super.key, required this.selectedDate});
@override
// ignore: library_private_types_in_public_api
_ScreenState createState() =>
_ScreenState(selectedDate: selectedDate);
}
class _ScreenState extends State<AllDATAsScreen> {
late final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey();
late Map<String, bool> expansionStates = {};
DateTime? selectedDate;
final int _selectedIndex = 0;
bool _isLoading = false; // Add this boolean variable to track loading state
@override
void initState() {
super.initState();
selectedDate = widget
.selectedDate; // Initialize selectedDate with the widget's selected date
}
@override
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldKey, // Add the GlobalKey to the Scaffold
appBar: AppBar(
//title: const Text('APP'),
title: Text(AppLocalizations.of(context)!.title),
titleSpacing: -1,
leading: IconButton(
icon: Image.asset('assets/Images/Fav.png'),
),
),
body: _isLoading
? Center(
child: CircularProgressIndicator(
backgroundColor: Colors.black,
valueColor: const AlwaysStoppedAnimation<Color>(
Color.fromRGBO(1, 203, 11, 0.75)),
strokeWidth: 5,
//semanticsLabel: 'Loading',
semanticsLabel: AppLocalizations.of(context)!.loading,
//semanticsValue: 'Loading',
semanticsValue: AppLocalizations.of(context)!.loading,
),
) // Show circular progress indicator when loading
: StreamBuilder<List<DATA>>(
stream: _DATAStreamController.stream,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(
backgroundColor: Colors.black,
valueColor: const AlwaysStoppedAnimation<Color>(
Color.fromRGBO(1, 203, 11, 0.75)),
strokeWidth: 5,
//semanticsLabel: 'Loading',
semanticsLabel: AppLocalizations.of(context)!.loading,
//semanticsValue: 'Loading',
semanticsValue: AppLocalizations.of(context)!.loading,
),
);
} else if (snapshot.hasError) {
return const Center(
child: Text('Failed to load data'),
);
} else if (!snapshot.hasData || snapshot.data!.isEmpty) {
return Center(
//child: Text('No data available'),
child: Text(AppLocalizations.of(context)!.nomatchesavailable),
);
} else {
....
....
....
return SingleChildScrollView(
child: ExpansionPanelList(
expandedHeaderPadding: EdgeInsets.zero,
children:
......
......
......
List<DATA> DATAs = entry.value;
Widget panelBody = Column(
children: DATAs.map<Widget>((DATA) {
return Padding(
padding: const EdgeInsets.only(
left: 5.0, bottom: 10.0),
child: Row(
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Center(
child: GestureDetector(
onTap: () {
final favoritesProvider = Provider.of<FavoritesProvider>(context, listen: false);
final isFavorite = favoritesProvider.isFavorite(DATA);
if (isFavorite) {
favoritesProvider.removeFromFavorites(DATA);
} else {
favoritesProvider.addToFavorites(DATA);
}
},
child: Icon(
Icons.star,
color: Provider.of<FavoritesProvider>(context).isFavorite(DATA) ? Colors.green : Colors.grey,
),
)
),
],
)
...........
...........
...........