如何初始化构造函数中的变量?



我正在学习如何使用干净的体系结构,我刚开始使用存储库(appwrite)并使用单例模式。现在我想让我的AuthService类接受一个存储库并继续。

然而,我在这门课上有一个问题:

import 'package:appwrite/appwrite.dart';
import 'package:mandi/infrastructure/repositories/appwrite_service.dart';
class AuthService {
final AppwriteService _appwriteService;
AuthService({AppwriteService appwriteService})
: _appwriteService = appwriteService;
Future<void> register(
String email,
String password,
String firstName,
String lastName,
) async {
final Account account = Account(_appwriteService.client);
account.create(
userId: ID.unique(),
email: email,
password: password,
name: '$firstName $lastName',
);
}
}

构造函数在'appwriteService'给出了一个错误,因为"参数'appwriteService'的值不能为'null',因为它的类型,但隐含的默认值是'null'。尝试添加一个显式的非'null'默认值或'required'修饰符。"

我刚刚在这个平台上看到':'后面是初始化字段,然而,编译器仍然抱怨它可能是空的。

我不知道如何解决这个问题。

请尝试以下代码组:

如果你想要命名构造函数你必须给required

AuthService({ required AppwriteService appwriteService})
: _appwriteService = appwriteService;

如果没有命名的构造函数,你可以这样使用:

AuthService(AppwriteService appwriteService)
: _appwriteService = appwriteService; 

最新更新