0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

CupertinoPickerでonSelectedItemChangedされた後に発動

Last updated at Posted at 2021-06-03

CupertinoPickerで選択するたびに発動するイベント(onSelectedItemChanged)はありますが、連続で発動するので負荷がかかる処理はしたくないところです。
Timerで選び終わった後に1回だけ発動させます。

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

//(略)

//Timerの設定
  Timer selectTimer;
  Timer _selectHandler() {
    if (selectTimer != null) {
      if (selectTimer.isActive) {
        selectTimer.cancel();
      }
    }

    return Timer(
      const Duration(seconds: 1),
      _select,
    );
  }

//最後に選択した1秒後に発動する
  void _select() {
    print(selectedArea);
  }
  
//CupertinoPickerが入っているWidget
  Widget _areaPicker(BuildContext context) {
    return GestureDetector(
      onTap: () {
        _showDemoPicker(
          context: context,
          child: BottomPicker(
            child: CupertinoPicker(
              backgroundColor:
                  CupertinoColors.systemBackground.resolveFrom(context),
              itemExtent: 30,
              children: areaList.map(_pickerItem).toList(),
              onSelectedItemChanged: (item) {
                setState(() => selectedArea = areaList[item]);
                selectTimer = _selectHandler();
              },
            ),
          ),
        );
      },
      child: Container(
          margin: EdgeInsets.fromLTRB(0, 0, 0, 20),
          padding: EdgeInsets.all(10.0),
          decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(5),
              border: Border.all(color: Colors.black12)),
          child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text(selectedArea),
                Icon(Icons.swap_vertical_circle, color: Colors.black45)
              ])),
    );
  }
  
  //(略)
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?