Mariam Younes
Mariam Younes

Reputation: 389

Method call on null when using shared preference

I want to use shared preference to keep user login and I'm using API with provider. I tried to put it in main but I don't how to do it because I have two different page to go so it was used in the first page but I found another error

[ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: NoSuchMethodError: The method 'login' was called on null. E/flutter ( 4199): Receiver: null

and this is the method which I used

UserProvider userProvider;
  ServiceProvider serviceProvider;
  bool alive = true;
  bool isLoading = false;
  var page;

  @override
  initState() {
    init();
    super.initState();
  }

  init() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    bool language = prefs.getBool('language');
    bool type = prefs.getBool('type');
    bool login = prefs.getBool('islog');
    if (alive) {
      if (language == true && type == true && login == true) {
        signIn();
      } else if ((language == true && type == false && login == true)) {
        visitor();
      }
    } else {
      if (alive) {
        setState(() {
          isLoading = false;
        });
      }
    }
  }

  signIn() async {
    //var res = await userProvider.residentLogin(context, phone, pass);
    SharedPreferences prefs = await SharedPreferences.getInstance();
    var phone = prefs.getString('phone');
    String pass = prefs.getString("pass");
    bool type = prefs.getBool('type');
      print("Shared ***************resident********************************");
      await userProvider.residentLogin(context, phone, pass);
      await serviceProvider.getHomeServiceList(context);
      await serviceProvider.getAdsList(context);
      await serviceProvider.getVideosList(context);
      Navigator.pushReplacement(context,
          MaterialPageRoute(builder: (context) => ResidentBottomTab()));
      print('Hello Tourist !!');
    
  }

  visitor() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    var phone = prefs.getString('phone');
    String pass = prefs.getString("pass");
    await userProvider.login(context, phone, pass);
    await serviceProvider.getVisitorAdsList(context);
    await serviceProvider.getVisitorVideosList(context);
    bool type = prefs.getBool('type');
    print("Shared ******************visitor*****************************");
    if (alive) {
      Navigator.pushReplacement(
          context, MaterialPageRoute(builder: (context) => VisitorHome()));
      print('Hello Tourist !!');
    }
  }

  @override
  void dispose() {
    alive = false;
    super.dispose();
  }

login method

Future<VisitorLoginModel> login(BuildContext context, phone, pass) async {
    final Map<String, dynamic> body = {
      'phone': phone,
      'password': pass,
      'token': '123',
      'serial_number': '123',
      'lang': 'en',
      'os': 'android',
    };

    _isLoading = true;
    notifyListeners();
    print('Starting request');
    http.Response response = await http.post(Environment.userLogin,
        body: json.encode(body), headers: Environment.requestHeader);
    print('Completed request');
    print('user SignUp response : ${response.body}');
    //print(body.toString());
    Map<String, dynamic> res = json.decode(response.body);
    var results;
    if (res['status'] == 1) {
      // login successful
      _visitorLoginModel = parseVisitorLogin(response.body);
      Provider.of<LoginVisitorUserProvider>(context, listen: false).userData =
          visitorLoginModel;
      Provider.of<LoginVisitorUserProvider>(context, listen: false)
          .sessionToken = visitorLoginModel.data.token;
      headers = Provider.of<LoginVisitorUserProvider>(context, listen: false)
          .httpHeader;
      // print('token');
      print('this is session token' +
          Provider.of<LoginVisitorUserProvider>(context, listen: false)
              .sessionToken);
    } else {
      // login failed;
      results =
          FailedRequest(code: 401, message: res['massage'], status: false);
    }
    _isLoading = false;
    notifyListeners();
    return visitorLoginModel;
  }

So has anyone an idea to solve this case?

Upvotes: 0

Views: 525

Answers (2)

Balaji Venkatraman
Balaji Venkatraman

Reputation: 1337

The issue here is the userProvider is being declared but not initialized and the same goes for serviceProvider

In Flutter any uninitialized variable will implicitly assigned with null So, at the line await userProvider.login(context, phone, pass); where you call login method in which userProvider is not only initialized

To Solve the issue do the following, In initState,

userProvider = Provider.of<UserProvider>(context, listen: false);

Upvotes: 1

dm_tr
dm_tr

Reputation: 4753

The method call await userProvider.login(context, phone, pass); is being done on a non initialized variable. UserProvider userProvider; has been declared but not initialized

Upvotes: 1

Related Questions