Home > Net >  Rebuild widget inside stack using bloc?
Rebuild widget inside stack using bloc?

Time:10-18

Is it possible to rebuild widget inside a stack using BlocBuilder? I tried a simple code below but it only rebuild the widget once. I want to rebuild the widget inside the stack which is the GoogleMapDetailsList and pass the search value. GoogleMapDetailsList also has different bloc that triggers in its InitState.

Column(
  children: [
    searchWidget(context),
    Expanded(
      child: Stack(
        children: [
          googleMap(),
          BlocBuilder<GoogleMapSearchBloc, GoogleMapSearchState>(
            builder: (context, state) {
              if (state is GoogleMapSearchInProgressState) {
                return GoogleMapDetailsList(
                  search: search,
                  goToPlaceCallback: _goToPlace,
                );
              } else if (state is GoogleMapSearchLoadInProgressState) {
                return CircularProgressIndicator();
              } else {
                return Container();
              }
            },
          ),

        ],
      ),
    ),
  ],
),


Row searchWidget(BuildContext context) {
    return Row(
      children: [
        ButtonTemplate(
            textPaddingInset: EdgeInsets.zero,
            text: 'Search',
            buttonColor: Theme.of(context).accentColor,
            onPressed: () {
              setState(() {
                searchResult = true;
              });

              BlocProvider.of<GoogleMapSearchBloc>(context)
                  .add(StartSearchEvent());

            })
      ],
  }

//BLOC
class GoogleMapSearchBloc
    extends Bloc<GoogleMapSearchEvent, GoogleMapSearchState> {
  GoogleMapSearchBloc() : super(GoogleMapSearchInitialState());

  @override
  Stream<GoogleMapSearchState> mapEventToState(
    GoogleMapSearchEvent event,
  ) async* {
    if (event is StartSearchEvent) {
      yield GoogleMapSearchLoadInProgressState();
      Future.delayed(const Duration(seconds: 5), () {});
      yield GoogleMapSearchInProgressState();
    }
  }
}

CodePudding user response:

I solved it by overriding didUpdateWidget() in GoogleMapDetailsList. I saw it in this answer. I also want to know if there is another way of doing this.

  @override
  void didUpdateWidget(GoogleMapDetailsList oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.search != widget.search) {
      BlocProvider.of<GoogleMapPlaceSearchBloc>(context)
          .add(RefreshGoogleMapPlaceSearchEvent());
    }
  }

CodePudding user response:

The app gets notified only once in this case. To subscribe for further changes use listen:true.

BlocProvider.of<GoogleMapSearchBloc>(context, listen:true)
.add(StartSearchEvent());
  • Related