我正在尝试创建一个功能,通过提供程序将项目添加到收藏夹屏幕。 当您单击图标时,颜色变为绿色,该项目被添加并保存在收藏夹屏幕上,但几秒钟后图标颜色再次变为灰色,就好像该项目不再在收藏夹中一样,尽管它是那里。 这是我的代码
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,
),
)
),
],
)
...........
...........
...........
在调用 loadfavorite 方法之前尝试使用 async 和 wait
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await SharedPreferences.getInstance();
runApp(
OverlaySupport(
child: MultiProvider(
providers: [
..........
],
child: Builder(
builder: (context) async {
final favoritesProvider = Provider.of<FavoritesProvider>(context, listen: false);
await favoritesProvider.loadFavorites(); // Wait for favorites to load
return const APP();
},
),
),
),
);
}