skip to Main Content
   IconButton(
                onPressed: () async {
                  DateTime? x = await showDatePicker(
                      context: context,
                      initialDate: DateTime.now(),
                      firstDate: DateTime.now(),
                      lastDate: DateTime(2040));
                  if (x == null) return;
                  setState(() {
                    final DateFormat formatter = DateFormat('yyyy-MM-dd');
                    String formattedDate = formatter.format(x);
                    print(formattedDate);
                    print(formattedDate.runtimeType);
                  });
                },
                icon: const Icon(UniconsLine.clock)),
            Text(formattedDate ?? "EMPTY"),

I am seeing always empty my formattedDate variable below on the build method why doesnt work this code

3

Answers


  1. Could you try to lift up the formattedDate? I think the Problem is that your variable is out of scope.

    class DatePicker extends StatefulWidget {
      const DatePicker({Key? key}) : super(key: key);
    
      @override
      State<DatePicker> createState() => _DatePickerState();
    }
    
    class _DatePickerState extends State<DatePicker> {
      String? formattedDate;
      @override
      Widget build(BuildContext context) {
        return Column(children: [
          IconButton(
              onPressed: () async {
                DateTime? x = await showDatePicker(
                    context: context,
                    initialDate: DateTime.now(),
                    firstDate: DateTime.now(),
                    lastDate: DateTime(2040));
                if (x == null) return;
                setState(() {
                  final DateFormat formatter = DateFormat('yyyy-MM-dd');
                  formattedDate = formatter.format(x);
                  print(formattedDate);
                  print(formattedDate.runtimeType);
                });
              },
              icon: const Icon(Icons.date_range)),
          Text(formattedDate ?? "EMPTY"),
        ]);
      }
    }
    
    Login or Signup to reply.
  2. The problem is in the scope of your variable formattedDate. It only exists inside setState because it was declared there.

    Declare it at the beginning of the class.

    Login or Signup to reply.
  3. You have redefined formattedDate inside setState() as a local variable. The field formattedDate you are using in Text(formattedDate ?? "EMPTY") is a totally different variable. It remains null, as you are not changing it at all. Just remove the String before formattedDate and it should be fine.

    final DateFormat formatter = DateFormat('yyyy-MM-dd');
    formattedDate = formatter.format(x); <-- This is your problem
    print(formattedDate);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search