我正在构建一个带有通知图标的应用程序,到目前为止,我所做的是显示通知图标,当我单击该图标时,该图标将更改为“ Icons.notifications_active”。但是,只有当我导航到新屏幕并移回到上一个屏幕并且如果我在onpressed函数中添加setstate()时,它才会更改或构建为活动通知图标。下面是代码
HomePage.dart
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();}
class _HomePageState extends State<HomePage> {
NotificationBloc notificationBloc;
@override
void initState() {
super.initState();
notificationBloc = BlocProvider.of<NotificationBloc>(context);}
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Column(
children: <Widget>[
BlocListener<NotificationBloc,
NotificationState>(
listener: (context, state) {},
child: BlocBuilder<NotificationBloc,
NotificationState>(
builder: (context, state) {
if (state is InitialNotificationState) {
return buildLoading();
} else if (state is NotificationLoadedState) {
return NotificationIconBuild(state.notification);
} else if (state is NotificationErrorState) {
return buildErrorUi(state.message1);}},),),],)]
Widget NotificationIconBuild(NotificationModle notification) {
return Column(
children: <Widget>[
notificationIcon("fajr", notification),],);}
Widget notificationIcon(String notification, NotificationModle notificationModle){
if(notificationModle.fajr == false)
return IconButton(
icon: Icon(Icons.notifications),
onPressed: (){
notificationModle.fajr = true;
notificationBloc.add(SelectNotificationEvent(notificationModle));},);
else return IconButton(
icon: Icon(Icons.notifications_active),
onPressed: (){
notificationModle.fajr = false;
notificationBloc.add(SelectNotificationEvent(notificationModle));},);
Notification_state.dart
class NotificationLoadedState extends NotificationState {
NotificationModle notification;
NotificationLoadedState({@required this.notification});
@override
List<Object> get props => [notification];
}
NotificationEvent.dart
class SelectNotificationEvent extends NotificationEvent {
NotificationModle notificationModle;
SelectNotificationEvent(this.notificationModle);
@override
List<Object> get props => null;
}
NotificationBloc.dart
class NotificationBloc extends Bloc<NotificationEvent, NotificationState> {
NotificationsRepositoryImp notificationsRepository;
NotificationBloc({@required this.notificationsRepository});
@override
NotificationState get initialState => InitialNotificationState();
@override
Stream<NotificationState> mapEventToState(
NotificationEvent event,
) async* {if(event is SelectNotificationEvent){
await notificationsRepository.saveNotifications(event.notificationModle);}}}
NotificationModle.dart
class NotificationModle{
bool fajr;
NotificationModle(this.fajr);}
NotificationsRepository.dart
class NotificationsRepositoryImp{
@override
Future<void> saveNotifications(NotificationModle notification) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setBool('n_fajr', notification.fajr); }}