如何在flutter中创建一个需要初始化的重用变量?

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

按照示例代码

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

  CloudBaseDatabase db = CloudBaseDatabase(core);

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

我想在不同的文件中使用这个变量collection,我该如何定义它?

我试图将其定义为class成员,但它警告说必须进行初始化。

谢谢!!

我加?避免空检查,但我不知道这是否是一个好的解决方案。

只需在助手 class 中维护所有属性并在构造函数中初始化所有属性,并通过将其作为参数传递到不同的 classes 中使用它们,

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;
}