flutterflutter-cupertino

I want to save the first initialized value in a TextFormField in a CupertinoPicker in Flutter


I want to save the first initialized value in a TextFormField in a CupertinoPicker. I've searched on Google and various forums, but it seems that I couldn't find a way to set the initial value as I want in CupertinoPicker. Is there really no way to do this?

it's front part

Container(
                                            child: HeightPicker(
                                              onSelectedItemChanged:
                                                  (selectedHeight) {
                                                // 선택 항목이 변경될 때의 동작
                                                // _heightController.text =
                                                //     '$selectedHeight cm';
                                                print(
                                                    'front : $selectedHeight cm');
                                                _heightController.text =
                                                    (selectedHeight).toString();
                                              },
                                            ),
                                          )

it's the widget code.

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class HeightPicker extends StatefulWidget {
  final ValueChanged<int> onSelectedItemChanged;

  // required this.onSelectedItemChanged,
  const HeightPicker({
    Key? key,
    required this.onSelectedItemChanged,
  }) : super(key: key);

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

class _HeightPickerState extends State<HeightPicker> {
  final ScrollController scrollController = ScrollController();
  late int _selected;
  // late int _onClicked;

  @override
  void initState() {
    super.initState();
    _selected = 20; // 초기 선택 항목
    // _onClicked = 15;
  }

  @override
  Widget build(BuildContext context) {
    return CupertinoPicker(
      itemExtent: 30,
      diameterRatio: 1,
      scrollController: FixedExtentScrollController(
        initialItem: _selected,
      ),
      children: List<Widget>.generate(45, (index) {
        // 150 ~ 190의 값
        int value = 150 + index;
        return Text('$value cm');
      }),
      onSelectedItemChanged: (int value) {
        setState(() {
          _selected = value;
          print('scrolling : $value');
          widget.onSelectedItemChanged(150 + value);
          // _heightController.text = (150 + value).toString();
        });
      },
    );
  }
}

I have tried various methods, but I have failed to retrieve the specified initial value into the text field. However, I am slowly digesting the situation while reviewing the reference 'Link'. Still, I wonder if there might be a solution.!


Solution

  • You can await for the modal to pop and check if the value has stayed the same. In that case you can reset to default/initial value (or whatever value you want). Example:

    ElevatedButton(
      onPressed: () async {
        final previousValue = date;
        await showCupertinoModalPopup<void>(
          context: context,
          builder: (_) {
            final size = MediaQuery.of(context).size;
            return Container(
              decoration: const BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(12),
                  topRight: Radius.circular(12),
                ),
              ),
              height: size.height * 0.27,
              child: CupertinoDatePicker(
                mode: CupertinoDatePickerMode.date,
                onDateTimeChanged: (value) {
                  date = value;
                  setState(() {});
                },
              ),
            );
          },
        );
        // no value was selected
        if (previousValue == date) {
          //back to default value which is DateTime.now() if initialDateTime is not provided to CupertinoDatePicker
          setState(() {
            final now = DateTime.now();
            date = DateTime(now.year, now.month, now.day);
          });
        }
      },
      child: const Text('Show Date Picker'),
    ),