Jonah Kornberg
Jonah Kornberg

Reputation: 183

Flutter setting variable of CupertinoPicker after showModalBottomSheet

I'm referencing this answer:https://stackoverflow.com/a/57592970/8616895

Trying to get selectedValue when the bottommodal is closed with WhenComplete.

The function in WhenComplete() is called, but when I print the selectedValue, it only responds as the default, 0. I have checked and SelectedValue does change as I rotate, but the correct value is not retrieved when I close the modal, I assume it has something to do with async or scope. Please share any suggestions.

My class is as follows:


class PopupButton extends StatefulWidget {
  final String initialValue;
  final List<dynamic> options;
  final Function callback;
  int initialIndex;
  PopupButton(
      {@required this.initialValue,
      @required this.options,
      this.callback,
      this.initialIndex = 0});

  @override
  _PopupButtonState createState() => _PopupButtonState();
}

class _PopupButtonState extends State<PopupButton> {
  int selectedValue;
  String text = "";
  void showPicker(
    BuildContext context,
  ) {
    showModalBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return Container(
            height: 200,
            child: CupertinoPicker(
                itemExtent: 32,
                onSelectedItemChanged: (value) {
                  if (mounted) {
                    setState(() {
                      selectedValue = value;
                    });
                  }
                },
                children: (widget.options.map((option) => Text(
                      option,
                      style: TextStyles.headerLight,
                    ))).toList()),
          );
        }).whenComplete(() {
// THIS ALWAYS PRINTS 0
      print("Selected: $selectedValue");
      if (widget.callback != null) {
        widget.callback(selectedValue);
      }
      TextEditingController();
      return;
    });
  }

  @override
  Widget build(BuildContext context) {
    selectedValue = widget.initialIndex;
    text = widget.initialValue;
    return GestureDetector(
      child: Text(text),
      onTap: () {
        showPicker(context);
      },
    );
  }
}

Upvotes: 0

Views: 716

Answers (1)

Reza M
Reza M

Reputation: 573

your mistake is initialization selectedValue in build method. Every time you call

setState(() {
  selectedValue = value;
});

the selectedValue initiated by widget.initialIndex.

Please move selectedValue = widget.initialIndex; to initState method.

@override
void initState() {
  super.initState();
  selectedValue = widget.initialIndex;
  text = widget.initialValue;
}

@override
  Widget build(BuildContext context) {
    return GestureDetector(
      child: Text(text),
      onTap: () {
        showPicker(context);
      },
    );
  }

Upvotes: 1

Related Questions