flutter 自定義城市選擇器

image.png

因?yàn)槌鞘羞x擇的數(shù)據(jù)是從服務(wù)器上拿的的落追,在pub上面也沒(méi)有找到合適插件吐绵,索性就自己寫(xiě)了一個(gè),在寫(xiě)的過(guò)程也遇到很多問(wèn)題慧妄,其實(shí)就是三個(gè) CupertinoPicker 組合在一起的,當(dāng)時(shí)寫(xiě)的過(guò)程中發(fā)現(xiàn) CupertinoPicker setState不更新 以及onSelectedItemChanged 調(diào)用的問(wèn)題
CupertinoPicker 不更新可以通過(guò) GlobalKey 來(lái)解決 onSelectedItemChanged 調(diào)用問(wèn)題可以通過(guò) NotificationListener監(jiān)聽(tīng)來(lái)拿到當(dāng)前的索引

這里分享一下實(shí)現(xiàn)代碼

import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:zhengda_health/app/custom_widgets/custom_text.dart';
import 'package:zhengda_health/app/http_util/http_api.dart';
import 'package:zhengda_health/app/http_util/http_util.dart';
import 'package:zhengda_health/app/support/app_color.dart';

//省市區(qū)類(lèi)型
enum CityType {
  province,
  city,
  area
}

class CityAlertView extends StatefulWidget {

  CityAlertViewDelegate delegate;
  CityAlertView({Key key,this.delegate}) : super(key: key);

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

class _CityAlertViewState extends State<CityAlertView> {

  List <CityAlertModel> _provinceList = [];

  List <CityAlertModel> _cityList = [];

  List <CityAlertModel> _areaList = [];

  GlobalKey _provinceGlobalKey = GlobalKey();

  GlobalKey _cityGlobalKey = GlobalKey();

  GlobalKey _areaGlobalKey = GlobalKey();

  int _provinceIndex = 0;

  int _cityIndex = 0;

  int _areaIndex = 0;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();


    _getAreaData(cityType:CityType.province,pid: '0' ,onSuccess: (){
      _getAreaData(cityType: CityType.city,pid: _provinceList.first.adcode,onSuccess: (){
          _getAreaData(cityType:  CityType.area,pid: _cityList.first.adcode,onSuccess: (){

          });
      });
    });

  }

  void _getAreaData({CityType cityType,String pid,Function onSuccess}){
    HttpUtil.getHttp('${HttpApi.areaInfo}?pid=$pid',onSuccess: (res){
      List<CityAlertModel> list =List<CityAlertModel>.from(res['areaLists'].map((it) => CityAlertModel.fromJson(it)));

      if(cityType == CityType.province){
        _provinceGlobalKey  =GlobalKey();;
        _provinceList = list ;

      }else if(cityType == CityType.city){

        _cityGlobalKey  =GlobalKey();;
        _cityList =list;
      }else{
        _areaGlobalKey  =GlobalKey();;
        _areaList = list;
      }
      setState(() {});
      onSuccess();

    });
  }

  //確定生成回調(diào)
  void _confirmClick(BuildContext context ){
    if(widget.delegate != null){
      widget.delegate.confirmClick([_provinceList[_provinceIndex],_cityList[_cityIndex],_areaList[_areaIndex]]);
    }
    Navigator.of(context).pop();

  }

  //取消
  void _canlClick(BuildContext context){
    Navigator.of(context).pop();
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(child: Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        SizedBox(height: 8,),
        _headerWidget(context),
        Row(
          children: [

            _pickerViewWidget(models:_provinceList,
                key:_provinceGlobalKey ,
                onSelectedItemChanged: (v){
              _provinceIndex = v;
              _getAreaData(cityType: CityType.city,pid: _provinceList[v].adcode,onSuccess: (){
                _getAreaData(cityType: CityType.area,pid: _cityList.first.adcode,onSuccess: (){
                });
              });

            }),

            _pickerViewWidget(models: _cityList,key:_cityGlobalKey,onSelectedItemChanged: (v){
              _cityIndex = v;
              _getAreaData(cityType: CityType.area,pid: _cityList[v].adcode,onSuccess: (){});
            } ),

            _pickerViewWidget(models: _areaList,key:_areaGlobalKey,onSelectedItemChanged: (v){
              _areaIndex =v;
            } ),
          ],
        )
      ],
    ));
  }

  Widget _headerWidget(BuildContext context){
    return Row(
      children: [
        _buttonWidget(title: '取消',textColor: Colors.black38,callback: (){
          _canlClick(context);
        }),
        Expanded(child: Container()),
        _buttonWidget(title: '確定',textColor: Colors.black,callback: (){
          _confirmClick(context);
        }),
      ],
    );
  }

  //piceerView
  Widget _pickerViewWidget({List<CityAlertModel> models,Key key,
    ValueChanged<int> onSelectedItemChanged,}){
    return Expanded(
        child: SizedBox(
            height: 200,
            child: NotificationListener(
              onNotification: (Notification scrollNotification) {
                  if (scrollNotification is ScrollEndNotification &&
                      scrollNotification.metrics is FixedExtentMetrics)
                  {
                    print((scrollNotification.metrics as FixedExtentMetrics).itemIndex); // Index of the list
                    onSelectedItemChanged((scrollNotification.metrics as FixedExtentMetrics).itemIndex);

                    return true;
                  } else {
                    return false;
                  }
              },
              child: CupertinoPicker(
                  key: key,
                  useMagnifier: true,
                  magnification: 1.2,
                  selectionOverlay: _selectionOverlayWidget(),
                  itemExtent: 34,
                  onSelectedItemChanged: (v){},
                  children: models.map((e) => _itemsWidget(e.name)).toList()),
            ))
    );
  }

  // 中間分割線(xiàn)
  Widget _selectionOverlayWidget(){
    return Padding(
      padding: EdgeInsets.only(left: 0, right: 0),
      child: Column(
        children: [
          Divider(
            height: 1,
            color: AppColor.green86Color,
          ),
          Expanded(child: Container()),
          Divider(
            height: 1,
            color: AppColor.green86Color,
          ),
        ],
      ),
    );
  }

  // cellItems
  Widget _itemsWidget(e){
    return Container(
      alignment: Alignment.center,
      child:  CustomText(e,fontSize: 14,),
    );
  }

  //公共button
  Widget _buttonWidget({String title ,Color textColor ,VoidCallback callback}){
    return  InkWell(
      onTap: callback,
      child: Container(
        alignment: Alignment.center,
        padding:EdgeInsets.only(left: 16,right: 16),
        height: 40,
        child: CustomText(title,color: textColor,),
      ),
    );
  }

}

abstract class  CityAlertViewDelegate{
  void confirmClick(List<CityAlertModel> models){}
}

class CityAlertModel {
  int id;
  String pAdcode;
  String adcode;
  String name;
  String level;
  String pinyin;
  String first;
  String lng;
  String lat;

  CityAlertModel(
      {this.id,
        this.pAdcode,
        this.adcode,
        this.name,
        this.level,
        this.pinyin,
        this.first,
        this.lng,
        this.lat});

  CityAlertModel.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    pAdcode = json['p_adcode'];
    adcode = json['adcode'];
    name = json['name'];
    level = json['level'];
    pinyin = json['pinyin'];
    first = json['first'];
    lng = json['lng'];
    lat = json['lat'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['p_adcode'] = this.pAdcode;
    data['adcode'] = this.adcode;
    data['name'] = this.name;
    data['level'] = this.level;
    data['pinyin'] = this.pinyin;
    data['first'] = this.first;
    data['lng'] = this.lng;
    data['lat'] = this.lat;
    return data;
  }
}

調(diào)用

class _AddAddressPageState extends State<AddAddressPage> implements CityAlertViewDelegate 
要implements 實(shí)現(xiàn)回調(diào)協(xié)議
  //回調(diào)省市區(qū)
  @override
  void confirmClick(List<CityAlertModel> models) {}

//調(diào)用彈框
  showModalBottomSheet(
        context: context,
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadiusDirectional.circular(10)),
        builder: (BuildContext context) {
          return CityAlertView(delegate: this,);
        });
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末展父,一起剝皮案震驚了整個(gè)濱河市返劲,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌犯祠,老刑警劉巖旭等,帶你破解...
    沈念sama閱讀 206,378評(píng)論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異衡载,居然都是意外死亡搔耕,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,356評(píng)論 2 382
  • 文/潘曉璐 我一進(jìn)店門(mén)痰娱,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)弃榨,“玉大人,你說(shuō)我怎么就攤上這事梨睁【ňΓ” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 152,702評(píng)論 0 342
  • 文/不壞的土叔 我叫張陵坡贺,是天一觀的道長(zhǎng)官辈。 經(jīng)常有香客問(wèn)我,道長(zhǎng)遍坟,這世上最難降的妖魔是什么拳亿? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 55,259評(píng)論 1 279
  • 正文 為了忘掉前任,我火速辦了婚禮愿伴,結(jié)果婚禮上肺魁,老公的妹妹穿的比我還像新娘。我一直安慰自己隔节,他們只是感情好鹅经,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,263評(píng)論 5 371
  • 文/花漫 我一把揭開(kāi)白布寂呛。 她就那樣靜靜地躺著,像睡著了一般瘾晃。 火紅的嫁衣襯著肌膚如雪贷痪。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 49,036評(píng)論 1 285
  • 那天酗捌,我揣著相機(jī)與錄音呢诬,去河邊找鬼。 笑死胖缤,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的阀圾。 我是一名探鬼主播哪廓,決...
    沈念sama閱讀 38,349評(píng)論 3 400
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼初烘!你這毒婦竟也來(lái)了涡真?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 36,979評(píng)論 0 259
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤肾筐,失蹤者是張志新(化名)和其女友劉穎哆料,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體吗铐,經(jīng)...
    沈念sama閱讀 43,469評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡东亦,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,938評(píng)論 2 323
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了唬渗。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片典阵。...
    茶點(diǎn)故事閱讀 38,059評(píng)論 1 333
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖镊逝,靈堂內(nèi)的尸體忽然破棺而出壮啊,到底是詐尸還是另有隱情,我是刑警寧澤撑蒜,帶...
    沈念sama閱讀 33,703評(píng)論 4 323
  • 正文 年R本政府宣布歹啼,位于F島的核電站,受9級(jí)特大地震影響座菠,放射性物質(zhì)發(fā)生泄漏狸眼。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,257評(píng)論 3 307
  • 文/蒙蒙 一辈灼、第九天 我趴在偏房一處隱蔽的房頂上張望份企。 院中可真熱鬧,春花似錦巡莹、人聲如沸司志。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 30,262評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)骂远。三九已至囚霸,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間激才,已是汗流浹背拓型。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 31,485評(píng)論 1 262
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留瘸恼,地道東北人劣挫。 一個(gè)月前我還...
    沈念sama閱讀 45,501評(píng)論 2 354
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像东帅,于是被迫代替她去往敵國(guó)和親压固。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,792評(píng)論 2 345