How to access one class method from another class in dart?
You could ensure a singleton instance of the class using a public factory constructor with a private regular constructor:
class Helper {
static Helper _instance;
factory Helper() => _instance ??= new Helper._();
Helper._();
...
}
If you call new Helper()
, you'll always get the same instance.
You need to import the file that contains class Helper {}
everywhere where you want to use it.
??=
means new Helper._()
is only executed when _instance
is null
and if it is executed the result will be assigned to _instance
before it is returned to the caller.
update
getUserDetailsFromSharedPreference
is async
and can therefore not be used in the way you use it, at least it will not lead to the expected result. getUserDetailsFromSharedPreference
returns a Future
that provides the result when the Future
completes.
class UserProfileState extends State<UserProfile> {
Helper helper = new Helper();
Future<Map> _userData; // this with ??= of the next line is to prevent `getUserDetailsFromSharedPreference` to be called more than once
Future<Map> get userData => _userData ??= helper.getUserDetailsFromSharedPreference();
}
If you need to access userData
you need to mark the method where you do with async
and use await
to get the result.
foo() async {
var ud = await userData;
print(ud);
}
To access other class method you can simply put static
on the method.
class Helper {
static printing(String someText){
print(someText);
}
}
void main() {
Helper.printing('Hello World!');
}