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 write a function result to instance variable

I have an error in 5 line

The instance member
‘generateId’ can’t be accessed in an initializer. Try replacing the
reference to the instance member with a different expression

what i shoud do to write a function result to instance variable?

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

import 'dart:math';


class User{
  int id = generateId(10); // error i here
  String firstName;
  String lastName;
  String eMail;
  String password;
  final DateTime regDate = DateTime.now();

  User(this.firstName, this.lastName, this.eMail, this.password,){
    id = generateId(10);
  }
  
  @override
  String toString() =>'User: \n$firstName \n$lastName';

  int generateId(int count){
    int result;
    List <int> nums = [];
    for (int i = 0; i < count; i++){
      nums.add((Random().nextInt(9) + 1).toInt());
    }
    result = int.parse(nums.join());
    return result;
  }
}





void main() {
  User newUser = User("D", "P", "example@ex.com", "password");

  print(newUser);
}

>Solution :

Well, since you have only a single constructor and that sets the id anyway, you can basically remove it:

This:

int id = generateId(10); // error i here

becomes:

late int id;

Done.

In case your really, really need that line, you could make the generateId method either a function instead of a class method, or you could make it static. That should work, too.

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