Flutter Chip的使用

已經是很久很久很久沒有更新了,這段時間過得略糟糕,此處省略一萬字。。。

感覺一眨眼,flutter都1.6了,落后了好多了,又重新撿起來熟悉了一遍,才想起來頁面咋創建的,好抱歉~~~~

昨晚偶然看到了一個比較好玩的組件,叫 Chip,應用場景(關于應用場景,這個鏈接說得很詳細)官方翻譯叫標簽或者芯片

一、效果

image
image
image
image

二、構造函數解析:

const Chip({
    Key key,
    this.avatar,//左側的圖標
    @required this.label,//這個是必填的參數,控件上顯示的文本
    this.labelStyle,
    this.labelPadding,
    this.deleteIcon,//右側的刪除圖標
    this.onDeleted,//刪除圖標的點擊事件,如果不寫該方法的話,deleteIcon顯示不出來
    this.deleteIconColor,
    this.deleteButtonTooltipMessage,//點擊刪除圖標后彈出的文本,類似于tooltip的效果
    this.shape,
    this.clipBehavior = Clip.none,//這個不曉得是啥
    this.backgroundColor,
    this.padding,
    this.materialTapTargetSize,//這個具體也不曉得怎么描述,它的兩個值,一個為padded,一個為shrinkWrap,前者自帶margin,后者好像沒有margin,緊貼附近的控件
    this.elevation,//陰影深度
    this.shadowColor,//陰影顏色
  })

三、例子

import 'package:flutter/material.dart';
import 'package:the_first_one/utils/PageUtil.dart';
import 'InputChipDemo.dart';
import 'FilterChipDemo.dart';
import 'package:fluttertoast/fluttertoast.dart';

class ChipPage extends StatefulWidget {
  @override
  _ChipPageState createState() => _ChipPageState();
}

class _ChipPageState extends State<ChipPage> {
  int _valueChoice = 0;

  Widget _buildChoiceItem(int index) {
    return ChoiceChip(
      label: Text("ChoiceChip $index"),
      selectedColor: Colors.orange, //選中的顏色
      disabledColor: Colors.orange[100], //沒選中的顏色
      onSelected: (bool selected) {
        setState(() {
          _valueChoice = selected ? index : null;
        });
      },
      selected: _valueChoice == index,
      labelStyle: TextStyle(color: Colors.black54),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("ChipDemo"),
      ),
      body: Center(
        child: SingleChildScrollView(
          child: Column(
            children: <Widget>[
              SizedBox(height: 10.0),
              Text("一、初步認識"),
              Divider(),
              Chip(
                label: Text("普通的chip"),
                labelStyle: TextStyle(color: Colors.black54),
                backgroundColor: Colors.orange,
              ),
              Chip(
                avatar: Icon(
                  Icons.arrow_forward,
                  color: Colors.black54,
                ),
                label: Text("帶avatar的chip"),
                labelStyle: TextStyle(color: Colors.black54),
                backgroundColor: Colors.orange,
              ),
              Chip(
                avatar: CircleAvatar(
                  backgroundImage:
                      AssetImage('assets/images/illustration_1.jpg'),
                  radius: 18.0,
                ),
                label: Text("帶avatar的chip"),
                labelStyle: TextStyle(color: Colors.black54),
                backgroundColor: Colors.orange,
              ),
              Chip(
                avatar: CircleAvatar(
                  backgroundImage:
                      AssetImage('assets/images/illustration_1.jpg'),
                  radius: 30.0,
                ),
                padding: EdgeInsets.all(0.0),
                label: Text("padding為0,labelPadding不為0的chip"),
                labelPadding: EdgeInsets.all(15.0),
                labelStyle: TextStyle(
                  color: Colors.black54,
                  fontSize: 10.0,
                  fontWeight: FontWeight.bold,
                ),
                backgroundColor: Colors.orange,
              ),
              Chip(
                label: Text("帶deleteIcon的chip"),
                deleteIcon: Icon(Icons.close),
                deleteIconColor: Colors.black54,
                onDeleted: () {
                  print("點擊了刪除噢");
                },
                deleteButtonTooltipMessage: "彈出提示",
                labelStyle: TextStyle(color: Colors.black54),
                backgroundColor: Colors.orange,
              ),
              Chip(
                label: Text("圓角矩形的chip"),
                deleteIcon: Icon(Icons.close),
                deleteIconColor: Colors.black54,
                onDeleted: () {
                  print("點擊了刪除噢");
                },
                deleteButtonTooltipMessage: "彈出提示",
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(2.0),
                ),
                labelStyle: TextStyle(color: Colors.black54),
                backgroundColor: Colors.orange,
              ),
              Chip(
                label: Text("尺寸最小的chip"),
                materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                labelStyle: TextStyle(color: Colors.black54),
                backgroundColor: Colors.orange,
              ),
              Chip(
                label: Text("帶陰影的chip"),
                shadowColor: Colors.grey,
                elevation: 10.0,
                labelStyle: TextStyle(color: Colors.black54),
                backgroundColor: Colors.orange,
              ),
              Divider(),
              Text("二、例子"),
              ActionChip(
                //自帶一個onPress事件,有點擊效果
                label: Text("ActionChip"),
                backgroundColor: Colors.orange,
                onPressed: () {
                  Fluttertoast.showToast(msg: "ActionChip");
                },
              ),
              Wrap(
                spacing: 5.0, //主軸間距
                runSpacing: 8.0, //副軸間距
                children: List<Widget>.generate(2, (int index) {
                  return _buildChoiceItem(index);
                }),
              ),
              RaisedButton(
                  child: Text(
                    "FilterChipDemo",
                    style: TextStyle(color: Colors.black54),
                  ),
                  color: Colors.orange,
                  onPressed: () {
                    PageUtil().pushTo(context, FilterChipDemo());
                  }),
              RaisedButton(
                  child: Text(
                    "InputChipDemo",
                    style: TextStyle(color: Colors.black54),
                  ),
                  color: Colors.orange,
                  onPressed: () {
                    PageUtil().pushTo(context, InputChipDemo());
                  }),
              SizedBox(height: 10.0),
            ],
          ),
        ),
      ),
    );
  }
}

四、其他

關于chip也可以看看以下擴展類,以下排列順序按照功能的升序排列

  1. ActionChip //比普通的chip多一個onPressed事件
  2. ChoiceChip //允許從一組選項中進行單一選擇
  3. FilterChip //自帶的比ChoiceChip多一個選中的勾勾的效果
import 'package:flutter/material.dart';

class FilterChipDemo extends StatefulWidget {
  @override
  _FilterChipDemoState createState() => _FilterChipDemoState();
}

class ActorFilterEntry {
  const ActorFilterEntry(this.name, this.initials);

  final String name;
  final String initials;
}

class _FilterChipDemoState extends State<FilterChipDemo> {
  final List<ActorFilterEntry> _cast = <ActorFilterEntry>[
    const ActorFilterEntry('Aaron Burr', 'AB'),
    const ActorFilterEntry('Alexander Hamilton', 'AH'),
    const ActorFilterEntry('Eliza Hamilton', 'EH'),
    const ActorFilterEntry('James Madison', 'JM'),
  ];
  List<String> _filters = <String>[];

  Iterable<Widget> get actorWidgets sync* {
    for (ActorFilterEntry actor in _cast) {
      yield Padding(
        padding: const EdgeInsets.all(4.0),
        child: FilterChip(
          avatar: CircleAvatar(child: Text(actor.initials)),
          label: Text(actor.name),
          selected: _filters.contains(actor.name),
          onSelected: (bool value) {
            setState(() {
              if (value) {
                _filters.add(actor.name);
              } else {
                _filters.removeWhere((String name) {
                  return name == actor.name;
                });
              }
            });
          },
        ),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("FilterChipDemo"),
      ),
      body: Column(
        children: <Widget>[
          Wrap(
            children: actorWidgets.toList(),
          ),
          Text('Look for: ${_filters.join(', ')}'),
        ],
      ),
    );
  }
}
  1. InputChip //比FilterChip多一個onPressed和onDeleted
import 'package:flutter/material.dart';

class InputChipDemo extends StatefulWidget {
  @override
  _InputChipDemoState createState() => _InputChipDemoState();
}

class _InputChipDemoState extends State<InputChipDemo> {
  List<String> list = [
    "搖滾",
    "音樂",
    "機車黨",
    "Android工程師",
    "全棧",
    "Python",
    "UI設計師",
    "測試小姐姐",
    "后臺單身狗",
    "產品老大",
    "路邊攤",
    "火鍋 串串 麻辣燙",
    "籃球",
    "攝影",
    "戶外",
    "客服",
    "超級自戀的小哥哥",
    "直播",
    "不忘初心 繼續前行",
    "記性不好",
    "花容月貌",
    "榴蓮控",
    "一定要穿美美的衣服"
  ];

  List<String> _filters = <String>[];

  Widget _buildItem(int index) {
    String content = list[index];
    return InputChip(
      avatar: CircleAvatar(
        backgroundImage: AssetImage('assets/images/illustration_1.jpg'),
        radius: 12.0,
      ),
      label: Text(
        content,
        style: TextStyle(fontSize: 12.0),
      ),
      shadowColor: Colors.grey,
      deleteIcon: Icon(
        Icons.close,
        color: Colors.black54,
        size: 14.0,
      ),
      onDeleted: () {
        setState(() {
          list.removeAt(index);
        });
      },
      onSelected: (bool selected) {
        setState(() {
          if (selected) {
            _filters.add(list[index]);
          } else {
            _filters.removeWhere((String name) {
              return name == list[index];
            });
          }
        });
      },
      selectedColor: Colors.orange,
      disabledColor: Colors.grey,
      selected: _filters.contains(list[index]),
      materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
      labelStyle: TextStyle(color: Colors.black54),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("InputChipDemo"),
      ),
      body: Container(
        padding: EdgeInsets.all(10.0),
        child: Wrap(
          spacing: 5.0,
          //主軸間距
          runSpacing: 8.0,
          //副軸間距
          alignment: WrapAlignment.end,
          //主軸上的對齊方式
          crossAxisAlignment: WrapCrossAlignment.center,
          //副軸上的對齊方式
          children: List<Widget>.generate(
            list.length,
            (int index) {
              return _buildItem(index);
            },
          ).toList(),
        ),
      ),
    );
  }
}

  1. RawChip //原始chip,通常僅在您想要創建自己的定制芯片類型時使用

五、補充

更多的應用場景,請點擊我

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,156評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,401評論 3 415
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,069評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,873評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,635評論 6 408
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,128評論 1 323
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,203評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,365評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,881評論 1 334
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,733評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,935評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,475評論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,172評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,582評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,821評論 1 282
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,595評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,908評論 2 372