Wajid khan
Wajid khan

Reputation: 872

Access other Class method in Flutter/dart

I was working on login with preference. Everything is working fine when I wrote all code in main.dart.

Problem:

When I create separate class on MySharePref then I am getting some error.

MySharePref.dart

import 'package:first_app/UserModel.dart';
import 'package:shared_preferences/shared_preferences.dart';

class SharePrefClass {


  void _saveData(UserModel model) async{

    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString("Username",model.userName);
    await prefs.setString("Password", model.password);
  }
  Future<UserModel> _getData() async{
    SharedPreferences preferences = await SharedPreferences.getInstance();
    String username =  preferences.getString("Username");
    String password = preferences.getString("Password");
    UserModel model = UserModel(username,password);
    return model;
  }

}

I want to access these both functions in main.dart:

_checkLogin() async {
     UserModel userModel = new UserModel(
      userNameEditText.text , passwordEditText.text); 

   SharePrefClass mySharedPref = new SharePrefClass();
   final UserModel returnModel = mySharedPref._getData() ;

    if(returnModel.userName == ""){
      print("No data");
    }else{
      print("else executed");
    }
  }

I am getting error:

enter image description here

Upvotes: 0

Views: 1760

Answers (1)

Shaode Lu
Shaode Lu

Reputation: 251

The prefix "_" means private field in dart.

Change the method name _getData() to getData() will let you can access this method in main.dart

Upvotes: 4

Related Questions