skip to Main Content

About getx i know that we can call Get.find for instance of controller which is created already

its working fine when i call Get.find in other screen, but while calling it in same screen its showing dynamic error,

"dynamic" not found. You need to call "Get.put(dynamic())" or "Get.lazyPut(()=>dynamic())"

in other screen its working fine..whats my mistake?

here is my code

i have floating action button to add data with controller and body for showing data,

class HomeScreen extends StatelessWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final  controller=Get.put(DataController());
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          int number=Random().nextInt(100);
          controller.add(number.toString());
        },
        child: Icon(Icons.add),
      ),
      appBar: AppBar(title:'Demo Page'),),
      body: BuildBody(),
    );
  }
}

body class


class BuildBody extends StatelessWidget {
  const  BuildBody ({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final controller=Get.find();//showing error
    return Obx(() => controller.isLoading.value?const CircularProgressIndicator():ShowData());
  }

  Widget ShowData() {
    return Text('Okay');
  }
}

2

Answers


  1. We need to tell the Getx to find which controller, otherwise it’ll show dynamic error. So,

    Do it like this:

    final controller = Get.find<DataController>();
    
    Login or Signup to reply.
  2. final controller=Get.find();
    

    above line will return dynamic as its common sense dear, how will it know which controller your are talking about… think about you have more than one controller

    like

    final controller1=Get.put(FoodController());
    final controller2=Get.put(MovieController());
    
    final controller=Get.find();
    

    here it will return dynamic bcz u have not mention type, so while calling Get.find() u have to mention which controller type.

    like

     final FoodController controller=Get.find();
    or
     final controller=Get.find<FoodController>();
    
    

    and better practise is that u should make a getter inside your class

    class DataController extends GetxController
    {
      static DataController get instance=>Get.find();
    
    }
    
    

    after initializing controller u can use anywhere like below

    final controller=DataController.instance;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search