0

Unhandled Exception: Bad state: Cannot emit new states after calling close,I need to solve this problem to make sure the state is sending over all screens.

I send the state every second and I tried to put the bloc in the homepage but it doesn't work

this cubit code

class OfficeCubit extends Cubit<OfficeStates>{
  OfficeCubit():super(firstState(master,room1,room2,hall1,hall2)){
    pup();
  }
  String? _now;
  Timer? _everySecond;

  static OfficeCubit get(context)=>BlocProvider.of(context);

 

  void pup () {
    s.prepareMqttClient();
    _now=DateTime.now().second.toString();

    _everySecond=Timer.periodic(Duration(seconds: 1), (Timer t)  async {
      _now = DateTime.now().second.toString();
      emit(firstState(master,room1,room2,hall1,hall2));
}

and this is the UI

Widget build(BuildContext context) {
return BlocProvider(
  create: (BuildContext context) =>OfficeCubit(),
  child: BlocBuilder<OfficeCubit,OfficeStates>(
    builder: (BuildContext context, state){
      var cubit = OfficeCubit.get(context);
      if (state is firstState){
        return Scaffold(..);
            
      }

      else {
        return CircularProgressIndicator();

      }
    },
  ),
);

the main.dart

Widget build(BuildContext context) {
return MaterialApp(
  debugShowCheckedModeBanner: false,
  theme: ThemeData(
    appBarTheme: AppBarTheme(
        elevation: 30.0,
        backgroundColor: Colors.blueGrey[900],
        toolbarHeight: 60.0,
        centerTitle: true,
        titleTextStyle: TextStyle(
          color:Colors.white70,
        )
    ),
  ),
  home: MyHomePage());
 }
}
Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56

1 Answers1

0

Wrap the MaterialApp with BlocProvider

Widget build(BuildContext context) {
  return MultiBlocProvider(
    providers: [
      BlocProvider<OfficeCubit>(
        create: (context) => OfficeCubit(),
      ),
    ],
    child: MaterialApp(
      debugShowCheckedModeBanner: false,
      //...
      home: MyHomePage(),
    ),
  );
}

And your and this is the UI will be

Widget build(BuildContext context) {
  return BlocBuilder<OfficeCubit,OfficeStates>(
    builder: (BuildContext context, state){
      
    }
  );
}
Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56