Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to initialize a variable in the constructor?

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.".

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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; 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading