Home > Software design >  "GetXController" not found. You need to call?
"GetXController" not found. You need to call?

Time:03-16

I want to implement GetX binding methods, and as result, I got this 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
main.dart

import 'package:donirajkrv/views/welcome.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import './router/index.dart';
import './bindings/user_binding.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      initialBinding: UserBinding(),
      home: const Scaffold(
        backgroundColor: Color.fromRGBO(244, 248, 252, 1),
        body: SafeArea(child: WelcomePage()),
      ),
      getPages: [...routeList],
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primaryColor: const Color(0XFFFB6394),
        appBarTheme: const AppBarTheme(
          systemOverlayStyle: SystemUiOverlayStyle.dark,
        ),
      ),
    );
  }
}

How main works:


void main() {
  Get.put<UserController>(UserController());
  runApp(const MyApp());
}
user_binding.dart
import 'package:get/get.dart';
import 'package:donirajkrv/controllers/user_controller.dart';

class UserBinding implements Bindings {
  @override
  void dependencies() {
    Get.put(() => UserController());
  }
}

Routelist:

import 'package:get/get.dart';
import '../views/welcome.dart';
import '../views/login.dart';
import '../views/register.dart';
import '../views/home_page.dart';
import '../middlewares/auth_middleware.dart';
import '../middlewares/back_to_home_middleware.dart';

// Routes path
import '../routes/index.dart';

List routeList = [
  GetPage(
      name: '/${Routes.WELCOME_PAGE}',
      page: () => const WelcomePage(),
      middlewares: [BackToHomeMiddleware()]),
  GetPage(
      name: '/${Routes.LOGIN_PAGE}',
      page: () => const Login(),
      middlewares: [BackToHomeMiddleware()]),
  GetPage(
      name: '/${Routes.REGISTER_PAGE}',
      page: () => const Register(),
      middlewares: [BackToHomeMiddleware()]),
  GetPage(
      name: '/${Routes.HOME_PAGE}',
      page: () => const HomePage(),
      middlewares: [AuthMiddleware()])
];

CodePudding user response:

you should make a simple change

Instead of

GetMaterialApp(
  initialBinding: BindingsBuilder(() {
    Get.put(UserBinding());
  })...

use

initialBinding: UserBinding())...

GetMaterialApp(
  initialBinding: UserBinding())...

In the user_binding.dart file you can initiate every controller that your app uses.

and then you can use it by simple declare a variable like this

UserController controller = Get.find();
//or like this:

final controller = Get.find<UserController>();
//I haven't tested the second one, but it should work.

Hope it works :)

You can also follow the example below: https://github.com/Prosa/Flutter-GetX-Bindings-Example

CodePudding user response:

  1. i have added the detail code for binding controller and increment function so try using this, it will definitely work
void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      initialBinding: UserBinding(),
      getPages: [...routeList],
      initialRoute: RouteNames.welcomePage,
      home: const Scaffold(
        backgroundColor: Color.fromRGBO(244, 248, 252, 1),
      ),
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primaryColor: const Color(0XFFFB6394),
        appBarTheme: const AppBarTheme(
          systemOverlayStyle: SystemUiOverlayStyle.dark,
        ),
      ),
    );
  }
}

class UserController extends GetxController {
  var i = 0.obs;
  void increment(){
    i  ;
  }
}
class RouteNames {
  static String welcomePage = "/welcomePage";
}
List routeList = [
  GetPage(
      name: '/${RouteNames.welcomePage}',
      page: () =>  WelcomePage(),
      ),
];
//here use binding like this 
class UserBinding implements Bindings {
  @override
  void dependencies() {
    Get.put<UserController>(UserController(), permanent: true);
  }
}
class WelcomePage extends StatelessWidget {
   WelcomePage({Key? key}) : super(key: key);
  // final userController = Get.put(UserController());
   final userController  = Get.find<UserController>();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
      ),
      body: Column(
        children: [
         Obx(() => Text(userController.i.value.toString(),
         style: const TextStyle(
           fontSize: 25,
           color: Colors.blueAccent
         ),),),
          ElevatedButton(onPressed: (){
            userController.increment();
          }, child: const Text("Button")),
        ],
      ),
    );
  }
}

  • Related