Search code examples
flutterdarthttprequesthttp-status-codesflutter-provider

How to get the status code from an http method created on a Provider in Flutter


I'm trying to modify the text from an Alert in a screen based on the status code of an http method, but I created the http method on another archive, which has a class with provider (changenotifier), how can I get the status code from the provider class into the screen I'm creating? I mean, I have this Provider archive:

import 'dart:convert';

import 'package:apetit_project/models/reservation.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class ReservationList with ChangeNotifier {
  List<Reservation> _items = [];
  List<Reservation> get items => [..._items];

  int get itemsCount {
    return _items.length;
  }

  void addReservation(Reservation reservation) {
    final future = http.post(
      Uri.parse(
          'http://$url/ords/apiteste/integrafoods/reservas'),
      headers: <String, String>{
        'Content-Type': 'application/json; charset=UTF-8',
      },
      body: jsonEncode(<String, String>{
        "id_usuario": reservation.userId.toString(),
        "usu_inclusao": reservation.userName.toString(),
        "id_cardapio": reservation.menuId.toString(),
        "hora_almoco": reservation.resTime.toString(),
        "cancelado_sn": reservation.canceledYn.toString(),
        'servido_sn': reservation.servedYn.toString(),
      }),
    );

    future.then((response) {
      _items.add(reservation);
    });
    notifyListeners();
  }
}

and I call the method this way in another archive:

void _newReservation() {
    final loggedUserList = Provider.of<LoggedUser>(context, listen: false);
    final newReservation = Reservation(
      userId: loggedUserList.loggedItems.first.id.toString(),
      userName: loggedUserList.loggedItems.first.name.toString(),
      menuId: widget.meal.menuId,
      resTime: dropDownValue,
      canceledYn: 'N',
      servedYn: 'N',
      altDate: '',
      restaurantId: '',
      service: '',
      userNo: '',
      userSector: '',
      menuDate: '',
    );
    Provider.of<ReservationList>(context, listen: false)
        .addReservation(newReservation);
  }

I want to call an alert that have two different messages, depending on what's the result from the http request, something like this:

void confirmReservation() {
      showDialog(
        context: context,
        builder: (context) {
          return const CustomAlert(
              message:
                  (statuscode = 200)?'Reserva confirmada!\n(O Cancelamento será permitidos apenas até as 9:00 do dia de consumo da reserva)': 'Erro! por favor, tente novamente!');
        },
      );
    }

How can I bring this status code to the archive where I'm importing this provider and achieve the result I want?


Solution

  • So what you could do is the following.

    • Convert your method into async function

      int? statusCode;
      
      void addReservation() async {
       final response = await http.post(
           Uri.parse('http://$url/ords/apiteste/integrafoods/reservas'),
           headers: <String, String>{
           'Content-Type': 'application/json; charset=UTF-8',
            },
        body: jsonEncode(<String, String>{
        "id_usuario": reservation.userId.toString(),
        "usu_inclusao": reservation.userName.toString(),
        "id_cardapio": reservation.menuId.toString(),
        "hora_almoco": reservation.resTime.toString(),
        "cancelado_sn": reservation.canceledYn.toString(),
        'servido_sn': reservation.servedYn.toString(),
      }),
      );
      
      statusCode = response.statusCode;
      if (response.statusCode == 200) {
         _items.add('reservation');
        } 
          notifyListeners();
         }
      

    and than what could do this this to check if there is an error or result

    final loggedUserList = Provider.of<LoggedUser>(context, listen:false);
    return const CustomAlert(
              message:
                  (loggedUserList.statusCode = 200) ? loggedUserList.items : 'error'