'Flutter: Can we navigate to other screen inside controller using GetX?

Can I use Get.to(OtherScreen()) inside Getx controller like the code below?

class UserController extends GetxController{

  Future<void> loginWithEmailAndPassword(
      {@required String email, @required String password}) async {
    
      await _firebaseAuth.signInWithEmailAndPassword(
        email: email.toLowerCase(),
        password: password,
      ).then((credential){
        Get.to(OtherScreen()); // Can I use this inside controller?
      });
  }
}


Solution 1:[1]

Answer is yes you can. Just pass the build context in your method and then use the navigation route

Future<void> loginWithEmailAndPassword(
  {@required String email, @required String password,@required BuildContext context}) async {

  await _firebaseAuth.signInWithEmailAndPassword(
    email: email.toLowerCase(),
    password: password,
  ).then((credential){
    Navigator.push(
    context,
    MaterialPageRoute(
      builder: (_) => OtherScreen(),
    ),; // Can I use this inside controller?
  });
}

Solution 2:[2]

Yes you can navigate in controller file just replace

Get.to(OtherScreen());

to

Get.to(()=> OtherScreen());

Both Working but second is right syntax to navigate using Getx

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Saddan
Solution 2 Ravi Limbani