1

Here is my Auth middleware:

import 'package:donirajkrv/controllers/user_controller.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

class AuthMiddleware extends GetMiddleware {
  final authService = Get.find<UserController>().isUserLogged; // Here is error, this line can't find UserController
  @override
  int? get priority => 1;
  bool isAuthenticated = false;

  @override
  RouteSettings? redirect(String? route) {
    isAuthenticated = true;
    if (isAuthenticated == false) {
      return const RouteSettings(name: '/login');
    }
    return null;
  }
}

A line from above (where is my comment) returns me an error:

════════ Exception caught by widgets library ═══════════════════════════════════
The following message was thrown building MyApp(dirty):
"UserController" not found. You need to call "Get.put(UserController())" or "Get.lazyPut(()=>UserController())"

The relevant error-causing widget was
MyApp
lib/main.dart:9

And middleware makes me that error.

...
 GetMaterialApp(
      initialBinding: UserBinding(),
...

I have tried to fix this with:

GetPage(
      name: '/${Routes.HOME_PAGE}',
      page: () => const HomePage(),
      binding: UserBinding(),
      middlewares: [AuthMiddleware()])

But again same error.

Milos N.
  • 4,416
  • 6
  • 18
  • 31

3 Answers3

0

I am here again, with a solution at this time :P

Please add this static method in your user_controller.dart file

static UserController get findOrInitialize{
    try{
      return Get.find<UserController>();
    }catch(e){
      //get controller is not initialized yet
      Get.put(UserController());
      return Get.find<UserController>();
    }
  }

In the initiation of the controller in user_bindings.dart file

instead of

@override
void dependencies() {
    UserController()
  }

do it like this:

@override
  void dependencies() {
    UserController.findOrInitialize;
  }

Finally, in the auth_middleware.dart file

initiate your controller like the example below:

final authService = UserController.findOrInitialize;

You can find the whole example here: https://github.com/Prosa/Flutter-GetX-Bindings-Example

  • May you also help on this question? https://stackoverflow.com/questions/70727549/how-to-create-an-authentication-middleware-for-a-flutter-app/71729168#71729168 –  Apr 22 '22 at 06:44
  • I saw your problem. I think that you can follow my example on github, download it and run it to check how it works, if you have any further questions, let me know, I will post a thorough answer. – Prodromos Sarakinou Apr 22 '22 at 23:46
  • Thank you for your response. I downloaded your code but I don't know why it gives me errors for all the import packages. –  Apr 24 '22 at 18:52
  • @ensan3kamel maybe you need to upgrade your flutter version – Prodromos Sarakinou Apr 25 '22 at 19:04
  • I could run your code but couldn't properly understand how to apply it to my problem? Or even it is my problem's solution or not? –  Apr 26 '22 at 00:48
  • I think just moving the line `Get.put(UserBinding());` solves the problem with less code. Please see refer to my answer. – Dabbel May 04 '22 at 14:03
0

Problem

The Middleware gets initialized before the Binding. (As to why this happens should be discussed with Getx.)

Solution

Move the Binding out of the method call initialBinding and place it somewhere else. This solution is a bit hacky, but solves the problem with one line of code.

Code Before

  @override
  Widget build(BuildContext context) {

    return GetMaterialApp(
      initialBinding: UserBinding(),
    ...

Code After

  @override
  Widget build(BuildContext context) {
 
    Get.put<UserBinding>(UserBinding()); // ADDED

    return GetMaterialApp(
      // initialBinding: UserBinding(),    REMOVED
    ...
Dabbel
  • 2,468
  • 1
  • 8
  • 25
0

I've fixed this by initializing the controller in the middleware file.

class AuthMiddleware extends GetMiddleware {

  @override
  RouteSettings redirect(String route) {
    final authService = Get.find<AuthService>();
    Get.put(RootController(), permanent: true); // here
    if (!authService.isAuth) {
      return RouteSettings(name: Routes.LOGIN);
    }
    return null;
  }
}
Abd ur Rehman
  • 183
  • 1
  • 2
  • 15