skip to Main Content

I am still new to flutter and learning how to deal with lists. In this case, I have a list of millisecondsSinceEpoch so (List<int> in Firestore) and I want to generate a new List<DateTime> of dates from those integers. However, I am not sure how to handle that with the DateTime.fromMillisecondsSinceEpoch().

The error is The argument type 'List<int>' can't be assigned to the parameter type 'int'. I understand it is not looking for a list, but not sure how to pass that properly.

//updatesDateEpoch is a list of int
 List<int> datesSec = logRecord.updatesDateEpoch.asList();

//error caused when passing dateSec
 List<DateTime> datesList = [DateTime.fromMillisecondsSinceEpoch(datesSec)];

2

Answers


  1. You are getting this error because the DateTime.fromMillisecondsSinceEpoch function is expecting a int parameter and you are passing the whole List, to simplify your code and solve the error you can do this:

    Code:

    //updatesDateEpoch is a list of int
    List<int> datesSec = logRecord.updatesDateEpoch.asList();
    
    //The new list in milliseconds
    List<DateTime> datesList = List.generate(datesSec.length, (index) => DateTime.fromMillisecondsSinceEpoch(datesSec[index]));
    

    List.generate takes two parameters:

    • The first is how long the list will be, in this case it’s the size of your previous list, so we pass datesSec.length as the first parameter.
    • The second parameter is the callback function that will receive the position of the element in this new list, we use this position to select a specific element in the previous list with datesSec[index] and then we pass the element in DateTime.fromMillisecondsSinceEpoch(datesSec[index]).

    And so a new millisecond list is successfully created.

    Login or Signup to reply.
  2. final datesList = datesSec.map(DateTime.fromMillisecondsSinceEpoch).toList();
    

    Aside: some people are working too hard at this. Whenever you have the form:

    (a) => someFunction(a)
    

    you should be getting a lint that says "unnecessary closure", because you can replace that with just:

    someFunction
    

    because the function name is indeed a function that takes a single value and returns a result!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search