Home > Enterprise >  Flutter, getting value from showTimePicker not working
Flutter, getting value from showTimePicker not working

Time:10-15

I am trying to displayed time selected from showTimePicker dialogue but after getting the value it becomes null again. after debugging, it seems like the value returned from future function expried or something. after the widgets onPress function it is back to null.

ElevatedButton(
                  child: const Text('Time'),
                  onPressed: () async {
                    vTimeSelected = await getTimeSelected(context);
                    setState(() {
                      // vStrToRndr = vTimeSelected.toString();
                      //print(vStrToRndr);
                    });
                  },
                ),
                ElevatedButton(
                  child: const Text('Solid'),
                  onPressed: () {
                    setState(() {
                      vDetail.solid = !vDetail.solid;
                    });
                  },
                ),
              ],
            ),
          ),
          if (vDetail.wet == true) Text('Nappy wet'),
          if (vDetail.solid == true) Text('Nappy Solid'),
          Text('Time: $vTimeSelected'),
[7:35 PM]
Future<TimeOfDay?> getTimeSelected(BuildContext context) async {
  TimeOfDay vTime = TimeOfDay(hour: 0, minute: 0);
  TimeOfDay? newTime =
      await showTimePicker(context: context, initialTime: vTime);

  return newTime;
  //print($newTime);
}

//thanks for any help

Text('Time: $vTimeSelected') //<---- this is displaying null

CodePudding user response:

You can follow this code structure. Make sure to declare variable outside the build method.

class TS extends StatefulWidget {
  const TS({super.key});

  @override
  State<TS> createState() => _TSState();
}

class _TSState extends State<TS> {
  TimeOfDay? vTimeSelected;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(onPressed: () async {
        vTimeSelected = await getTimeSelected(context);
        setState(() {});
      }),
      body: Text("${vTimeSelected}"),
    );
  }
}
  • Related