flutter 按鈕單選封裝


數字是自己先寫死的

 List list =[
    {
      "title": "影視特效",
      "type":0,
    },
    {
      "title": "室內設計",
      "type":1
    },
    {
      "title": "游戲原畫",
      "type":2
    },
    {
      "title": "次時代",
      "type":3
    },
    {
      "title": "UI設計",
      "type":4
    },
    {
      "title": "后期合成",
      "type":5
    },
  ];

使用了GridView

用來控制一行顯示幾列

@override
  Widget build(BuildContext context) {
    int groupValue=1;
    return GridView.count(
      padding: EdgeInsets.all(5.0),
      //一行多少個
      crossAxisCount: 3,
      //滾動方向
      scrollDirection: Axis.vertical,
      // 左右間隔
      crossAxisSpacing: 10.0,
      // 上下間隔
      mainAxisSpacing: 15.0,
      //寬高比
      childAspectRatio: 1 / 0.4,
      shrinkWrap: true,
      children: widget.formList.map((value) {
        return listitem(context,value);
      }).toList(),
    );
  }
widget.formList 是從調用頁面傳過來的
 Widget listitem(context,value) {
    var deviceSize = MediaQuery.of(context).size;
    print(value['type']);
    return groupValue==value['type'] ? RaisedButton(
      color: Colors.black,
      onPressed: (){
        print('切換${value}');
        updateGroupValue(value['type']);
      },
      child: Text(value['title'],style: TextStyle(color: Colors.white),),
    ):OutlineButton(
      onPressed: (){
        print('切換${value}');
        updateGroupValue(value['type']);
      },
      child: Text(value['title']),
    );
  }
這里是代碼的關鍵比較 當value和groupValue一致的時候則選中 設置選中樣式和沒選中樣式

 

當點擊某一個按鈕的時候進行修改 groupValue 的值 默認groupValue值為0

int groupValue=0;

void updateGroupValue(int v){ setState(() { groupValue=v; }); }

  最終效果如下:

 

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM