我正在Dart / Flutter中为我的应用程序构建模型。这是一个模型的样子:
class AnyController {
public function anyFunction(MyService $myService)
{
// $this->myService->foo()
}
}
这些模型将存储在abstract class Model {
/// A unique identifier of the model.
/// Gets generated by Firestore.
final String id;
Model(this.id);
}
class MyModel extends Model {
final String name;
final String description;
final int order;
MyModel(String id, this.name, this.items, this.order) : super(id);
}
集合中的Google Firestore中:
mymodels
要从Firestore中获取这些模型的列表,我需要将mymodels/abc
mymodels/def
...
类型的收集路径(mymodels
)存储在某个地方。所以以后可以在获取模型时使用它:
MyModel
该收集路径存储在哪里?我当时在考虑在Future<List<T>> fetchList() {
// How to know `path` by knowing T?
_firestore.collection('path').getDocuments()
}
接口中声明一个静态属性,但是Dart似乎不允许重写静态属性。
Dart注释适合吗?
答案 0 :(得分:0)
不幸的是,我来到的最佳选择是使collectionPath
成为班级成员。这是Dart / Flutter的存储库模式示例:
class FirebaseRepository<T extends Model> extends Repository<T> {
final Firestore _firestore;
final String _collectionPath;
FirebaseRepository(this._firestore, this._collectionPath)
: assert(_firestore != null),
assert(_collectionPath != null);
@override
Future<List<T>> fetchList() async {
final snapshot =
await _firestore.collection(_collectionPath).getDocuments();
// TODO: Map snapshot documents to [T] and return.
}
用法:
final Repository<MyModel> repository = FirebaseRepository(_firestore, 'mymodels');
答案 1 :(得分:-1)
如果要保存要在各处使用并可以用作字符串的硬编码变量,则可以使用由静态变量组成的类。 假设您在Firebase中有一些收藏。
您可以将它们保存在这样的类中:
class Path {
static String modelA = "mymodels/modelA";
static String modelB = "mymodels/modelB";
static String exampleC = "mymodels/exampleC";
static String exampleD = "mymodels/exampleD";
}
,然后在您的代码中访问它们,它将解析为String
。
例如:Firestore.instance.collection(Path.modelA)
可以通过编程和动态方式进行访问。只要导入了创建此类的文件,您就可以在任何地方访问它。