Home > database >  I have an error like the non-nullable variable 'sessionUser' must be initialized
I have an error like the non-nullable variable 'sessionUser' must be initialized

Time:12-17

I have an error like:

The non-nullable variable 'sessionUser' must be initialized. try adding an initializer expression...

I searched a lot on the net but I did not find a solution to my problem. Can you help me to solve this problem?

import 'dart:convert';
import 'package:flutter/widgets.dart';
import 'package:shared_preferences/shared_preferences.dart';

class UserModel {
    String id;
    String nom;
    String email;

    UserModel({
        required this.id,
        required this.nom,
        required this.email
    });

    static UserModel sessionUser;

    factory UserModel.fromJson(Map<String,dynamic> i) => UserModel(
        id: i['id'],
        nom: i['nom'],
        email: i['email']
    );

    Map<String,dynamic> toMap() => {
        "id": id,
        "nom": nom,
        "email": email
    };

    static void saveUser(UserModel user) async {
        SharedPreferences pref = await SharedPreferences.getInstance();
        var data = json.encode(user.toMap());
        pref.setString("user", data);
        pref.commit();
    }

    static void getUser() async {
        SharedPreferences pref = await SharedPreferences.getInstance();
        var data = pref.getString("user");
        if (data != null) {
            var decode = json.decode(data);
            var user = await UserModel.fromJson(decode);
            sessionUser = user;
        } else {
            sessionUser = UserModel();
        }
    }

    static void logOut() async {
        SharedPreferences p = await SharedPreferences.getInstance();
        p.setString("user", null);
        sessionUser = null;
        p.commit();
    }
}

CodePudding user response:

your variable sessionUser is not initialized. Try something like this :

static UserModel? sessionUser;

The ? means the variable can be null, so you'll have to check if the variable is null before using later in your code.

  • Related