Bloc: BlocProvider udpate value

Created on 11 May 2020  路  9Comments  路  Source: felangel/bloc

hi team,

sorry i kindly new and like to know how to update the state inside Class without context.
here for example :

class totalearnamountbloc extends Bloc{

@override
String get initialState => '0';

@override
Stream mapEventToState(String totalearnamount) async* {
yield totalearnamount.toString();
}
}

class a (){
BlocProvider.of(context).add("Test udpate");
}

on class a will error cause no context there.
please your advice.
thank you

question

Most helpful comment

thankyou RollyPeres and felangel. i think need to learn more again.

thanks alot.

All 9 comments

Hi @kartzhai ! 馃憢

You would need to inject the bloc into your class.

class Test {
    Test(Bloc<String, String> bloc): _bloc = bloc;
    final Bloc<String, String> _bloc;

    void addNewText() {
        _bloc.add("Test udpate");
    }
}

i try this but seems not work.

a(Bloc totalcashamountbloc): a = totalearnamountbloc ;

class a(){
}

on different dart file and not inside statefull or stateless widget.

@kartzhai you need to access the bloc via context and inject it into the class.

Where are you creating an instance of class a in relation to your widget tree?

ops sorry guys! put on the wrong places. it work but let me try and review several time.
btw i think i have 3-4 bloc to update. then i just need to inject them all inside class right?

guys sorry, i found some issue again. i like to update the bloc inside abloc class. abloc will get data from api and then update the state totalearnamountbloc.

for example :

class abloc extends Bloc, List>{

abloc (Bloc totalcashamountbloc): totalcashamountbloc = totalcashamountbloc;
Bloc totalcashamountbloc;

@override
// TODO: implement initialState
List get initialState => [];

@override
Stream> mapEventToState(List event) async* {
// TODO: implement mapEventToState

List<Modal> list=[];

try {

  final response = await http.post(xxxxx,
      body: {
      xx
      });
  final data = jsonDecode(response.body);
  if (data.length != 0) {

totalcashamountbloc .add("Test udpate");
} else {

  }
} catch (e) {
  print("");
  print(e);
}

yield list;

}
}

but i try to create the BlocProvider like below:
BlocProvider< abloc >(
create :(context) => abloc (),
),

the error mention 1 positional argument expected but 0 found,

please your advice

Please have a look at bloc-to-bloc communication

Closing this for now but feel free to comment with additional questions and I'm happy to continue the conversation 馃憤

thankyou RollyPeres and felangel. i think need to learn more again.

thanks alot.

Don't we all?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

nerder picture nerder  路  3Comments

Reidond picture Reidond  路  3Comments

abinvp picture abinvp  路  3Comments

RobPFarley picture RobPFarley  路  3Comments

komapeb picture komapeb  路  3Comments