Set selected initial CupertinoPicker chosen index

14.2k views Asked by At

I am new in Flutter development, I'm trying to CupertinoPicker inside showCupertinoModalPopup which triggered by clicking CupertinoButton.

After choosing the Provinsi (Province), I can repick the Province by clicking again on the button, but It should be the item that I did choose.

Here's my code

showCupertinoModalPopup(
  context: context,
  builder: (_) {
    return new SizedBox(
    height: MediaQuery.of(context).size.height / 2,
    child: new CupertinoPicker(
      magnification: 1.2,
      useMagnifier: true,
      itemExtent: 32.0,
      onSelectedItemChanged: (i) => setState(() => _chosenProvince = listProvince[i]),
      children: r != null && listProvince != null ? listProvince.map((prov) {
      return new Padding(
        padding: const EdgeInsets.all(4.0),
        child: new Text(
        prov.name,
        textAlign: TextAlign.center,
        overflow: TextOverflow.ellipsis,
          style: new TextStyle(
          fontSize: 20.0,
        ),
      ),
    );
  }).toList(): [],),);});

Is there any initialValue or something for CupertinoPicker to set to?

2

There are 2 answers

4
Dinesh Balasubramanian On BEST ANSWER

You can use FixedExtentScrollController to set the initialValue. Refer to this

0
Jonathan Rhein On

As described by Dinesh Balasubramanian you can use FixedExtentScrollController to set the initialValue

It will look like this, e.g. to start at the fourth element:

showCupertinoModalPopup(
  context: context,
  builder: (_) {
    return new SizedBox(
    height: MediaQuery.of(context).size.height / 2,
    child: new CupertinoPicker(
      scrollController: FixedExtentScrollController(initialItem: 3),
      magnification: 1.2,
      useMagnifier: true,
      itemExtent: 32.0,
      onSelectedItemChanged: (i) => setState(() => _chosenProvince = listProvince[i]),
      children: r != null && listProvince != null ? listProvince.map((prov) {
      return new Padding(
        padding: const EdgeInsets.all(4.0),
        child: new Text(
        prov.name,
        textAlign: TextAlign.center,
        overflow: TextOverflow.ellipsis,
          style: new TextStyle(
          fontSize: 20.0,
        ),
      ),
    );
  }).toList(): [],),);});