Home > Net >  Can I create single instance of Get.find<>()?
Can I create single instance of Get.find<>()?

Time:11-09

Currently to display value from controller I am using next construction:

Get.find<XMLFilesStatController>().foo.value,
Get.find<XMLFilesStatController>().bar.value,
Get.find<XMLFilesStatController>().baz.value,

Can I create in class single instance that point to Get.find<XMLFilesStatController>() ?

Something like: var xmlCtrl = Get.find<XMLFilesStatController>();

and then use it as: xmlCtrl.foo?

I tried to do it like:

class XMLProcessingStatisticView extends StatelessWidget {
  var formKey = GlobalKey<FormState>();

  var xmlCtrl = Get.find<XMLFilesStatController>();

On main.dart I am creating:

main() {
  //....
  Get.lazyPut<XMLFilesStatController>(() => XMLFilesStatController());

  runApp(MyApp());
}

So instance XMLFilesStatController is initialized. But I need way to shortcut Get.find

But got an error:

errors.dart:202 Uncaught (in promise) Error: "XMLFilesStatController" not found. You need to call "Get.put(XMLFilesStatController())" or "Get.lazyPut(()=>XMLFilesStatController())"

enter image description here

CodePudding user response:

You can do exactly what you described, but your problem is that you haven't instantiated XMLFilesStatController yet. You first have to use Get.put(XMLFilesStatController()); or Get.lazyPut(()=>XMLFilesStatController());.

After that you can just use var xmlCtrl = Get.find<XMLFilesStatController>(); like you said.

Take a look at dependency management.

CodePudding user response:

You need to use Get.put(XMLFilesStatController()) or Get.lazyPut(()=>XMLFilesStatController()) at first. Then you can create your object by calling var xmlCtrl = Get.find<XMLFilesStatController>(); .

If you want your XMLFilesStatController object to be permanent i.e. you want to create the object for only one time and use it for whole app lifecycle, then you need to do this Get.put(XMLFilesStatController(),permanent=true)

  • Related