How to use a Bloc Pattern to manage 2 widgets in Flutter

Asked

Viewed 118 times

0

I’m implementing Bloc in my app, in order to componentize widgets, but I am unable to receive the status changes of a Widget that is in the Widgetprincipal class to change another that is in the Widgetsecundario class, from the stream, It turns out that the Bloc Class print shows the modification, but apparently Bloc.output, in Widgetsecundario does not receive the changes.

I put the 2 widgets in the same class to test, it worked, but I can’t keep it that way, because 1 widget is my app bar and the other is part of the body, and if Widgetsecundario is called, appBar needs to increase in size, which you can’t do dynamically, so they’re in different blocks.

Creates a managerial class

import 'dart:async';

class ClasseBloc{
  bool ativador = false;


  final StreamController<bool> _streamController = StreamController();
  Sink<bool> get input => _streamController.sink;
  Stream<bool> get output => _streamController.stream;

  void alterarCondicaoAativador(){ // Aqui modifico o estado da variavél.
    ativador = !ativador ;
    print(ativador );
    input.add(ativador ); // Adciono ao canal
  }
}

I have a class with a function that calls the Bloc alternator

class WidgetPrincipal extends StatelessWidget  implements PreferredSize {


  WidgetPrincipalBloc bloc = WidgetPrincipalBloc();
  //bool ativador= false;
  @override
  Size get preferredSize => const Size.fromHeight(56);
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: <Widget>[
          AppBar( // CABEÇALHO
            elevation: 0,
            title: "Um texto qualquer",
            actions: <Widget>[
              IconButton(
                  icon: Icon(Icons.menu,color: Colors.white),
                  onPressed: (){
                    bloc.alterarCondicaoAativador(); // Aqui chamo o alternador do Bloc
                  }
              )
            ],

          ),

I created another class pro Widget that I want to change the visibility, as the Button of the Main Widget class Bloc.changeCondicationActivator();

class WidgetSecundario extends StatelessWidget {
  WidgetPrincipalBlock bloc = WidgetPrincipalBlock();
  @override
  Widget build(BuildContext context) {
    return Container(
      child: StreamBuilder<bool>(
          stream: bloc.output, // Leitura de alteraçães de estado
          builder: (context, snapshot){
            print("VALOR ${bloc.ativador}"); // >>Problema<< O valor aqui só é lido a primeira vez, depois não recebe mais atualizações
            return exibirWidgetDesejado(bloc.ativador);
          }
      ),
    );

    Widget abrirWidgetDesejado(visibilidade){ // EXIBIÇÃO OU OCULTAÇÃO DO WIDGET
      return Visibility(
      visible: visibilidade,
      child: Container()
      );
    }
  }

1 answer

0

Browser other questions tagged

You are not signed in. Login or sign up in order to post.