Home > Blockchain >  Adding data to list in initState for show it as DropdownMenuItem
Adding data to list in initState for show it as DropdownMenuItem

Time:10-21

class _MyHomePageState extends State<MyHomePage> {
  TimeOfDay dropdownvalue = TimeOfDay(hour: 1, minute: 1);
  late List<TimeOfDay> TimeList = [];
  @override
  void initState() {
    Future.delayed(Duration.zero, () async {
      await PickTime(9, 20);
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            DropdownButton<TimeOfDay>(
              hint: const Text('Pick a Date'),
              value: dropdownvalue,
              items: TimeList.map((TimeOfDay vvalue) {
                return DropdownMenuItem<TimeOfDay>(
                    child: Text(vvalue.toString()), value: vvalue);
              }).toList(),
              onChanged: (TimeOfDay? value) => () {
                setState(() {
                  if (value != null) dropdownvalue = value;
                });
              },
            )
          ],
        ),
      ),
    );
  }

  Future<void> PickTime(int begin, int end) async {
    for (int i = begin; i < end; i  ) {
      TimeOfDay t = TimeOfDay(hour: i, minute: 0);
      TimeList.add(t);
      t = TimeOfDay(hour: i, minute: 30);
      TimeList.add(t);
    }
  }
}

I want to make an appointment application.It got an empty list which i want to fill it in the PickTime function. When i call this function in initState it bypasses function and the list remains empty. Because of that Dropdownbutton has no items to show it. How can i call this function proper way to fill this list ?

CodePudding user response:

You need to call setState({}) method after fill the list. Build view need to reload.

CodePudding user response:

changing the PickTime method, and adding setState to the end will do the job:

  Future<void> PickTime(int begin, int end) async {
    for (int i = begin; i < end; i  ) {
      TimeOfDay t = TimeOfDay(hour: i, minute: 0);
      TimeList.add(t);
      t = TimeOfDay(hour: i, minute: 30);
      TimeList.add(t);
    }

    setState(() {});
  }
  • Related