0

I'm getting data from the api and show them as list then choose particular index to delete data from the list and from the database too. actually that particular Item is being deleted from the database but need to trigger get data api again then list will be updated.

Oh sorry I forgot to mention that I'm using flutter_bloc.

PIECE OF CODE:

List<AlertData> recordings;
class RecordingsScreen extends StatelessWidget {
  final void Function() onPop;
  const RecordingsScreen({Key key, this.onPop}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: MyTheme.white,
      appBar: AppBar(
        elevation: 0,
        backgroundColor: MyTheme.primaryColor,
        automaticallyImplyLeading: false,
        title: Row(
          children: [
            IconButton(
                icon: Icon(
                  Icons.arrow_back_ios,
                  color: MyTheme.secondryColor,
                ),
                onPressed: onPop),
            Text(
              "RECORDINGS",
              style: TextStyle(
                color: MyTheme.secondryColor,
              ),
            ),
          ],
        ),
      ),
      body: BlocProvider(
        create: (context) => AlertBloc()..add(GetOldAlerts()),
        child: BlocBuilder<AlertBloc, AlertState>(
          builder: (BuildContext context, AlertState state) {
            if (state.alertStatus == AlertStatus.gettingOldAlertsFailed ||
                state.alertStatus == AlertStatus.deletionAlertFailed) {
              return _OldAlertFailed(
                error: state.res['message'],
              );
            }
            if (state.alertStatus == AlertStatus.gotOldAlerts ||
                state.alertStatus == AlertStatus.deletedAlert ||
                state.alertStatus == AlertStatus.deletionAlert) {

               recordings = [];
               recordings =
                  BlocProvider.of<AlertBloc>(context).oldAlertModel;
             
              return _bodyForm(state);
            }
            return Center(
              child: ProcessingIndicator(),
            );
          },
        ),
      ),
    );
  }
  _bodyForm(AlertState state ){
    return Stack(
      children: [
        _RecordingsForm(),
        state.alertStatus == AlertStatus.deletionAlert 
        ? _DeletionProcessBar()
        :Container()
      ],
    );
  }
}

List of items which are being fetched from the api



class _RecordingsForm extends StatefulWidget {
  @override
  __RecordingsFormState createState() => __RecordingsFormState();
}

class __RecordingsFormState extends State<_RecordingsForm> {

  @override
  Widget build(BuildContext context) {
    return Container(
        child: ListView.builder(
            itemCount: recordinds.length,
            itemBuilder: (context, index) {
              return ListTile(
                  trailing: recordinds[index].isPlaying
                      ? Image.asset(
                          PLAYING_ASSET,
                          height: 20,
                          width: 20,
                        )
                      : PopupMenuButton(
                          elevation: 3,
                          child: Image.asset(
                            VERTICAL_MENU_ASSET,
                            height: 20,
                            width: 20,
                          ),
                          itemBuilder: (_) => <PopupMenuEntry<String>>[
                                new PopupMenuItem(
                                    value: "DELETE",
                                    height: 10,
                                    child: Row(
                                      children: [
                                        Text(
                                          "DELETE",
                                          style: TextStyle(
                                              fontSize: 13,
                                              fontWeight: FontWeight.bold),
                                        ),
                                        SizedBox(width: 4),
                                        Image.asset(
                                          DELETE_ASSET,
                                          height: 13,
                                          width: 13,
                                        ),
                                      ],
                                    ))
                              ],
                          onSelected: (val) => BlocProvider.of<AlertBloc>(context).add(DeleteAlert(
                                recordinds[index].alertId.toString()))), //HERE DELETE ITEM EVENT GOT TRIGGERED.
                  contentPadding: ...,
                     
                  leading: ...,
                  title: ...);
            }));
  }


}

Here is the short_video of issue

Shruti Ramnandan Sharma
  • 4,027
  • 13
  • 44
  • 76
  • 1
    How do you fetch the items to be displayed on the List using BloC? You can just call it again after deleting the item to refresh the List. – Omatt Sep 21 '21 at 12:26
  • OMG , How I can be so dumb. Yeah you are right, `if (state.alertStatus == AlertStatus.deletedAlert) { BlocProvider.of(context).add(GetOldAlerts()); }`. This is so simple. BTW Thank you so much for realising my stupidity. – Shruti Ramnandan Sharma Sep 21 '21 at 12:34

1 Answers1

1

As previously mentioned in the comments, you can just simply call refresh the List after deletion by calling the Bloc method that populates the List initially.

The reason why the List isn't refreshed is because the Bloc provider that you're calling just simply deletes the item from the List. Another way that you can do is by updating the StreamController during deletion so the BlocProvider will be rebuilt again with the fresh/updated List.

Here's an example but I'm using StreamBuilder. A similar approach could be applied on your issue.

class AlbumsBloc {
  final _repository = Repository();
  final _albumFetcher = StreamController<List<AlbumModel>>();

  /// bloc.allAlbums is set as stream on StreamBuilder
  /// i.e.
  /// StreamBuilder(
  ///   stream: bloc.allAlbums,
  ///   ...
  /// ),
  Stream<List<AlbumModel>> get allAlbums => _albumFetcher.stream;

  fetchAlbum() async {
    /// In this sample, Repository contains HTTP requests 
    /// to fetch List<AlbumModel>
    List<AlbumModel> listAlbums = await _repository.fetchAllAlbums();
    /// Add the List on Stream
    _albumFetcher.sink.add(listAlbums);
  }

  deleteAlbumItem(String albumItem){
    /// HTTP request to delete album item
    await _repository.deleteAlbumItem(id: albumItem);
    /// Fetch albums again
    List<AlbumModel> listAlbums = await _repository.fetchAllAlbums();
    /// Update the Stream
    _albumFetcher.sink.add(listAlbums);
  }

  dispose() {
    _albumFetcher.close();
  }
}

final bloc = AlbumsBloc();
Omatt
  • 8,564
  • 2
  • 42
  • 144
  • Can you explain how will I use StreamController with flutter_bloc? Actually I had used for real time data changes but not able to handle it so removed it. – Shruti Ramnandan Sharma Sep 22 '21 at 04:34
  • I'm can provide an example using StreamBuilder, but a similar approach could be applied on your issue. – Omatt Sep 22 '21 at 05:25