Home > Back-end >  How to initialize a variable in the constructor?
How to initialize a variable in the constructor?

Time:01-23

I'm learning how to use clean architecture and I just started with the repository (appwrite) and used a singleton pattern. Now I want my AuthService class to take a repository and continue.

However I have a problem in this class:

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',
    );
  }
}

The constructor gives an error at 'appwriteService' because "The parameter 'appwriteService' can't have a value of 'null' because of its type, but the implicit default value is 'null'. Try adding either an explicit non-'null' default value or the 'required' modifier.".

I just read on this platform that after the ':' comes the initializer field, however, the compiler still complains about it being possibly null.

I don't know how to solve this.

CodePudding user response:

Please try the below code bloc :

if you want name constructor you have to give required

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

Without named constuctor you can use like :

 AuthService(AppwriteService appwriteService)
      : _appwriteService = appwriteService; 
  • Related