'Error: NoSuchMethodError: The getter 'sessionToken' was called on null

Hello fellow programmers! I am starting in the world of Flutter programming. I am following a course on Udemy, the questions are never answered by the teacher and I would not like to stop with that error.

Url https://www.udemy.com/share/104Olo3@xtvsGS5hu0gc1eh3tVazmbv3OIlbZpdoTIVPBSMn7Aqe4JCMKpyLdiZyz4xW7vM5/

Cap: 104

I have my App in Flutter with Dart and my database developed in SQL and NodeJs.

My error is when I enter the Administrator role When I enter I get this error

I/chatty  ( 8221): uid=10154(com.agave.agave_investment_app) 1.ui identical 2 lines
I/flutter ( 8221): Error: NoSuchMethodError: The getter 'sessionToken' was called on null.
I/flutter ( 8221): Receiver: null
I/flutter ( 8221): Tried calling: sessionToken
I/flutter ( 8221): SESION TOKEN: JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjExIiwiZW1haWwiOiJob2xhQGdtYWlsLmNvbSIsImlhdCI6MTYzOTAwMDMzMH0.4QqRnRMVK1X7K2ni2zU7SxACt8tAs4-ynu9WAKiHBTQ
I/chatty  ( 8221): uid=10154(com.agave.agave_investment_app) 1.ui identical 2 lines
I/flutter ( 8221): SESION TOKEN: JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjExIiwiZW1haWwiOiJob2xhQGdtYWlsLmNvbSIsImlhdCI6MTYzOTAwMDMzMH0.4QqRnRMVK1X7K2ni2zU7SxACt8tAs4-ynu9WAKiHBTQ

I am printing the sessionToken from the database to check that if it arrives and is correct, if it is arriving, in my provider I have this Function where it should be receiving the authorization

Future<List<Order>> getByStatus(String status) async{     //consulta para obtener todas las categorias
    try {
      print('SESION TOKEN: ${sessionUser.sessionToken}');
      Uri url = Uri.http(_url, '$_api/findByStatus/$status');
      Map<String, String> headers = {
        'Content-type': 'application/json',
        'Authorization': sessionUser.sessionToken
      };
      final res = await http.get(url, headers: headers);
      if(res.statusCode == 401) {
        Fluttertoast.showToast(msg: 'Sesion expirada');
        new SharedPref().logout(context, sessionUser.id);
      }
      final data = json.decode(res.body);  //se obtienen las ordenes
      Order order = Order.fromJsonList(data);
      return order.toList;
    }

The model where 'sessionToken' comes from is this

class User {

  String id;
  String name;
  String lastname;
  String email;
  String phone;
  String password;
  String sessionToken;
  String image;
  List<Rol> roles = [];
  List<User> toList = [];

  User({
    this.id,
    this.name,
    this.lastname,
    this.email,
    this.phone,
    this.password,
    this.sessionToken,
    this.image,
    this.roles
  });

  factory User.fromJson(Map<String, dynamic> json) => User(
      id: json["id"] is int ? json['id'].toString() : json["id"],
      name: json["name"],
      lastname: json["lastname"],
      email: json["email"],
      phone: json["phone"],
      password: json["password"],
      sessionToken: json["session_token"] ,
      image: json["image"],
      roles: json["roles"] == null ? [] : List<Rol>.from(json['roles'].map((model) => Rol.fromJson(model))) ?? [],
  );

  User.fromJsonList(List<dynamic> jsonList) {
    if (jsonList == null) return;
    jsonList.forEach((item) {
      User user = User.fromJson(item);
      toList.add(user);
    });
  }

  Map<String, dynamic> toJson() => {
    "id": id,
    "name": name,
    "lastname": lastname,
    "email": email,
    "phone": phone,
    "password": password,
    "session_token": sessionToken,
    "image": image,
    "roles": roles,
  };
}

This is my method in Visual Studio Code

async findByStatus(req, res, next) {        //metodo para obtener el status de la orden
        
        try {
            const status = req.params.status;
            const data = await Order.findByStatus(status);
            console.log(`Status: ${JSON.stringify(data)}`);               
            return res.status(201).json(data); 
        }
         catch (error) {
            console.log(`Error ${error}`);
            return res.status(501).json ({
                message: 'Hubo un error al tratar de obtener las ordenes por estado',
                error: error,
                success: false
            })
        }
    },

Table created in SQL

SELECT
            O.id,
            O.id_client,
            O.id_address,
            O.id_delivery,
            O.status,
            O.timestamp,
            JSON_AGG(
                JSON_BUILD_OBJECT(
                    'id', P.id,
                    'name', P.name,
                    'description', P.description,
                    'price', P.price,
                    'image1', P.image1,
                    'image2', P.image2,
                    'image3', P.image3,
                    'quantity', OHP.quantity    
                )
            ) AS products,
            JSON_BUILD_OBJECT(
                'id', U.id,
                'name', U.name,
                'lastname', U.lastname,
                'image', U.image
            ) AS client,
            JSON_BUILD_OBJECT(
                'id', A.id,
                'address', A.address,
                'neighborhood', A.neighborhood,
                'lat', A.lat,
                'lng', A.lng
            ) AS address
        FROM
            orders AS O
        INNER JOIN 
            users AS U
        ON 
            O.id_client = U.id
        INNER JOIN
            address AS A
        ON
            A.id = O.id_address
    INNER JOIN
        order_has_products AS OHP
    ON
        OHP.id_order = O.id
    INNER JOIN 
        products AS P
    ON
        P.id = OHP.id_product
    WHERE
            status = $1
    GROUP BY
        O.id, U.id, A.id;

I initialize sessionUser first

class OrdersProvider {
  String _url = Environment.API_AGAVE;
  String _api = '/api/orders';
  BuildContext context;
  User sessionUser;

  Future init(BuildContext context, User sessionUser)  async {
      this.context = context;
      this.sessionUser =  sessionUser;
  }


  Future<List<Order>> getByStatus(String status) async{     //consulta para obtener todas las categorias
    try {
      print('SESION TOKEN: ${sessionUser.sessionToken}');
      Uri url = Uri.http(_url, '$_api/findByStatus/$status');
      Map<String, String> headers = {
        'Content-type': 'application/json',
        'Authorization': sessionUser.sessionToken
      };
      final res = await http.get(url, headers: headers);
      if(res.statusCode == 401) {
        Fluttertoast.showToast(msg: 'Sesion expirada');
        new SharedPref().logout(context, sessionUser.id);
      }
      final data = json.decode(res.body);  //se obtienen las ordenes
      Order order = Order.fromJsonList(data);
      return order.toList;
    }

    catch(e){
      print('Error: $e');
      return [];
    }
  }

What do you think can cause me this error?? Thanks in advance



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source