Search code examples
flutterdartbloccubit

Why is my bloc throwing an exception condition?


All hello, I have a screen, when opened, a request flies to the server, it returns 400 error status to me, but why does it not get into an error state, but gets into an exception, why?

I should hit when the status is not 200 in the block (status is OrderFinishError), but I hit throw StateError('err');

Here are my states -

    abstract class OrderFinishState {}
    
    class OrderFinishNotLoading extends OrderFinishState {}
    
    class OrderFinishLoading extends OrderFinishState {}
    
    class OrderFinishLoaded extends OrderFinishState {
      OrderFinishLoaded({required this.orderFinishModels});
      final OrderFinishModels orderFinishModels;
    }
    
    class OrderFinishError extends OrderFinishState {
      OrderFinishError({required this.errorModels});
      final ErrorModels errorModels;
    }

My сubit -

    class OrderFinishCubit extends Cubit<OrderFinishState> {
  OrderFinishCubit() : super(OrderFinishNotLoading());

  Future<void> orderFinish() async {
    emit(OrderFinishLoading());

    final prefs = await SharedPreferences.getInstance();
    final token = prefs.getString('token');

   final  orderId = prefs.getInt('orderId');

    final response = await http.post(Uri.parse(ConfigUrl.orderFinish),
        headers: {
          "Content-Type": "application/vnd.api+json",
          "Accept": "application/vnd.api+json",
          "Authorization": "Bearer $token",
        },
        body: jsonEncode(<String, dynamic>{
          "order_id": orderId,
        }));

    if (response.statusCode == 200) {
      log('test order finish cubit');
      log(orderId.toString());
      final responseJson = json.decode(response.body) as Map<String, dynamic>;
      log(json.decode(response.body).toString());
      emit(OrderFinishLoaded(
          orderFinishModels: OrderFinishModels.fromJson(responseJson)));
    } else {
      final jsonError = json.decode(response.body) as Map<String, dynamic>;
      log(response.statusCode.toString());
      log(json.decode(response.body).toString());
      emit(OrderFinishError(errorModels: ErrorModels.fromJson(jsonError)));
    }
  }
}

My BlocBuilder -

    return BlocProvider<OrderFinishCubit>(
            create: (context) => OrderFinishCubit()..orderFinish(),
            child: Scaffold(
              body: BlocBuilder<OrderFinishCubit, OrderFinishState>(
                builder: (context, state) {
                  if (state is OrderFinishNotLoading) {
                    return Center(
                      child:
                          Text('Дождитесь загрузки или перезапустите приложение'),
                    );
                  } else if (state is OrderFinishLoading) {
                    return const Center(
                      child: CircularProgressIndicator(),
                    );
                  } else if (state is OrderFinishLoaded) {
                    return Home();
                  } else if (state is OrderFinishError) {
                    Scaffold(
                        body: SafeArea(
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Text(state.errorModels.message),
                          SizedBox(
                            height: 15,
                          ),
                          InkWell(
                              onTap: () async {
                                context.go('/activeTravel');
                              },
                              child: Container(
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(32),
                                    color: ConfigColor.green,
                                  ),
                                  width: width,
                                  height: 44,
                                  child: Center(
                                    child: Text('На главную',
                                        textAlign: TextAlign.center,
                                        style: TextStyle(
                                            color: Colors.white,
                                            fontSize: 16,
                                            fontWeight: FontWeight.w500)),
                                  ))),
                        ],
                      ),
                    ));
                  }
                  throw StateError('err');
                },
              ),
            ));

Please note that I have a similar code, only on a different screen and it works well.

Please help me, this is the last task in the project))


Solution

  • It is because you are not returning the Scaffold widget.

    Change

    else if (state is OrderFinishError) {
                        Scaffold(
                            body: SafeArea(
    

    to

    else if (state is OrderFinishError) {
                       return  Scaffold(     // 👈 add return here
                            body: SafeArea(