0

Is it a good practice (or at least possible) to trigger an event during a state change in flutter with flutter_bloc? As in:

if (state is SomeState) {
  _bloc.add(Event())
}

My use case in this scenario is to trigger a modal as reaction to some state change, however everytime I do this (tried with BlocListener and BlocBuilder) the modal is always triggered twice, as in you have to close 2 modals.

I have to do this because I do 2 api calls, each event triggering one call PostEvent and GetEvent let's say, and I want the modal to open only after the second one is finished.

PostEvent -> Request -> StateChange -> Builder -> add(GetEvent) -> Request -> StateChange -> Builder -> showModal()

I was also wondering if I should do both calls in the same method but haven't tested that yet.

After doing some digging I found that that even though the Event was only added once, the Widget was rebuilding 2 times with the same state (GetFinished e.g) therefore showing the 2 modals.

Any help would be appreciated.

Thanks

Jorge Lima
  • 157
  • 15

1 Answers1

0

If I understood correctly, I would sugest you to do this:

1 - Make your statefull widget listening the bloc.stream, on initState (Remember to cancel subscription on dispose)

2 - On listen new Data, you triger that modal

3 - After the request, you call _bloc.add() method to triger modal.

4- Example:

import 'dart:async';

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('test')),
        body: BodyWidget(),
      ),
    );
  }
}

class BodyWidget extends StatefulWidget {
  @override
  BodyWidgetState createState() {
    return new BodyWidgetState();
  }
}

class BodyWidgetState extends State<BodyWidget> {
  StreamSubscription subscription;

  @override
  void initState(){
    super.initState();
    subscription = _bloc.yourStream$.listen((data) async {
      await showDialog(context: context);
    });
  }

  @override
  void dispose() {
    subscription?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

As you can see, I'm talking just about stream flow, without using any external 3rd package.

This should work properly