How to write a function result to instance variable

Viewed 37

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?

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);
}
2 Answers

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.

You should make the generateId method static.

The method does not need access to the object, it uses no instance methods or fields, so it can, and should, be declared static.

(It can also be significantly simplified.)

static int generateId(int count){
  var result = 0;
  var random = Random();
  for (var i = 0; i < count; i++) {
    result = result * 10 + random.nextInt(9) + 1;
  }
  return result;
}

Also consider whether you really need all digits to be non-zero, or you just need the first digit to be non-zero. If so, you can do:

 final int id = 1000000000 + Random().nextInt(9000000000);

to get a random ten-digit identifier.

Related