skip to Main Content

I am trying to assign the length of a list to a double and it says that an instance member can’t be accessed in an initializer:

List numlist = [1,2,3,4,5];
double size = numlist.length.toDouble();

Is there a way to get this to work?

2

Answers


  1. use late to declare a variable that will be initialized at a later time

    List numlist = [1,2,3,4,5];
    late double size = numlist.length.toDouble();
    

    in this case, size should be initialized after numlist

    Login or Signup to reply.
  2. Use Getter: Dynamically computes the size whenever it is accessed, ensuring it is always up-to-date with the current length of the list.

    For example:

      List<int> numlist = [1, 2, 3, 4, 5];
    
      double get size {
        return numlist.length.toDouble();
      }
      
      void test() {
        final result = size;
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search