flutterflutter-layoutflutter-datetime-pickerflutter-date-range-picker

The instance member 'noww' can't be accessed in an initializer


i have this date picker in my app, and i want the last date to be 3 years ago from the time using the app how can i solve it, i tried to give the last date now.year -3 but it doesn't work! it keeps tell me that 'The instance member 'noww' can't be accessed in an initializer.'

  var noww = DateTime.now();
  DateTime selectedDate = DateTime(noww.year - 3);
showDatePicker(
        context: context,
        initialDate: selectedDate, // Refer step 1
        firstDate: DateTime(now.year - 10),
        lastDate: DateTime(now.year + 1),

Solution

  • Declare the variable now like this

    var noww;
    

    But then after that, run the rest of the code in initState(), like this

    @override
    void initState(){
      super.initState();
      noww = DateTime.now();
      DateTime selectedDate = DateTime(noww.year - 3);
      showDatePicker(
        context: context,
        initialDate: selectedDate, // Refer step 1
        firstDate: DateTime(now.year - 10),
        lastDate: DateTime(now.year + 1),
      );
    }
    
    @override
    Widget build(context){
      ...
    }
    

    This is because you cannot use initialisers outside of functions.