Home > Software design >  date can't see on the screen with setstate
date can't see on the screen with setstate

Time:12-14

   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

CodePudding user response:

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"),
    ]);
  }
}

CodePudding user response:

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.

CodePudding user response:

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);
  • Related