Search code examples
flutterglobal-variables

How to create a reused variable in flutter,which needs to be initialized?


Following the example code

void main() async {
  CloudBaseCore core = CloudBaseCore.init({'env': 'your-env-id'});

  CloudBaseDatabase db = CloudBaseDatabase(core);

  Collection collection = db.collection('user');
}

I want to use this variable collection in different files, so how can I define it?

I tried to define it as a class member,but it warned that initialization is must.

Thanks!!


Solution

  • Just maintain all the properties in a helper class and initialize all the properties inside the constructor and use them into the different classes by passing it as a parameter,

    void main() async {
      DataBaseHelper helper = DataBaseHelper();
    
      // Now, you can use helper.collection to all your classes. 
      helper.collection;
    }
    
    class DataBaseHelper {
      DataBaseHelper() {
        core = CloudBaseCore.init({'env': 'your-env-id'});
        db = CloudBaseDatabase(core);
        collection = db.collection('user');
      }
    
      late CloudBaseCore core;
    
      late CloudBaseDatabase db;
    
      late Collection collection;
    }