0

I have implemented a class in a file user_service.dart:

class UserService { 
    Future<User> createUser(...)

 ....
}

I have tried referencing the createUser method in another class

I import the User Service class

  import 'user_service.dart';

and try

  UserService userService;
  print(userService.toString());

  UserService.createUser(....);

It compiles fine.

A am getting an error: NoSuchMethodError: The method 'createUser' was called on null.

Any ideas?

Help appreciated.

Kevin Dev
  • 221
  • 1
  • 3
  • 8
  • 3
    To access `createUser` you need an instance from `UserService` `UserService()` creates an instance. `UserService().createUser()` would work. If you don't want multiple `UserService` instances, you need to create it on a single place and pass it around or use something like a singleton pattern. https://stackoverflow.com/questions/12649573/how-do-you-build-a-singleton-in-dart – Günter Zöchbauer Dec 19 '18 at 11:38
  • If you need to access createUser() method from the class UserService you can declare your method as a static member like this` static Future createUser(...) ;` – Saed Nabil Dec 19 '18 at 11:58
  • 1
    Have you create an instance of that class? ```UserService service = UserService(); service.createUser()``` – Linh Dec 19 '18 at 12:16
  • Did not create the instance - thank you. Using a singleton is also a good idea. – Kevin Dev Dec 19 '18 at 13:29

1 Answers1

2

In your case you need firstly create a new instance of you UserService class.

UserService _instance = UserService(); // here you are creating a new instance with a default constructor

//now you can call your UserService methods
_instance.createUser();
Marcos Boaventura
  • 4,641
  • 1
  • 20
  • 27