Flutter中一次只能选中一个复选框

时间:2019-09-28 11:46:00

标签: flutter

我的应用程序中有3个复选框,这些复选框是通过在复选框上循环而形成的,在我的应用程序中它允许选择多个复选框,但我不希望发生这种情况,一次只能选择一个扑通扑通。

下面是我的代码。

class _DashboardFilterState extends State<DashboardFilter> {

 void showModalSheet() {
 List<Map<String, Object>> tickbox;
 timeData = [
      {"id": "1", "displayId": "Daily"},
      {"id": "2", "displayId": "Weekly"},
      {"id": "3", "displayId": "Monthly"}
    ]; 

   showModalBottomSheet<void>(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(10.0),
        ),
        context: context,
        builder: (BuildContext context) {
          return StatefulBuilder(
              builder: (BuildContext context, StateSetter state) {
            return createBox(context, timeData, state);
          });
        });
 }

createBox(BuildContext context,List<Map<String, Object>> tickbox, StateSetter state) {
          var tickboxdata = tickbox.map<Widget>((data) {
          int id = data["id"];
          var dispId = data["displayId"];
          return buildTimeData(context, id, dispId, state);

        }).toList();

      return SingleChildScrollView(
          child: LimitedBox(
            child: Column(
              mainAxisSize: MainAxisSize.max,
              mainAxisAlignment: MainAxisAlignment.center,
              // children: metrics,
              children: <Widget>[
              Container(
                  child: Column(
                    children: tickboxdata,
                  ),
                ),
               ],
            )),
          );
    }


     Widget buildTimeData(
          BuildContext context, var id, var disp, StateSetter state) {
        return Container(
            child: Column(mainAxisSize: MainAxisSize.min, 
         children: <Widget>[
          CheckboxListTile(
              value: widget.timeSelected[id],
              title: Text(disp),
              controlAffinity: ListTileControlAffinity.leading,
              onChanged: (bool val) {
                manageTimeState(val, id, state);
              })
        ]));
      }

    void manageTimeState(bool val, var id, StateSetter state) {
        state(() {
          widget.timeSelected[id] = val;
        });
      }

让我知道是否还有其他选择,谢谢

1 个答案:

答案 0 :(得分:0)

请使用软件包https://pub.dev/packages/grouped_buttons
在onSelected中,如果选择了多个

,则删除第一个选择的项目

代码段

List<String> _checked = [];
... 
CheckboxGroup(
        labels: <String>[
          "Sunday",
          "Monday",
          "Tuesday",
          "Wednesday",
          "Thursday",
          "Friday",
          "Saturday",
        ],
        disabled: ["Wednesday", "Friday"],
        checked: _checked,
        onChange: (bool isChecked, String label, int index) =>
            print("isChecked: $isChecked   label: $label  index: $index"),
        onSelected: (List selected) => setState(() {
          if (selected.length > 1) {
            selected.removeAt(0);
            print('selected length  ${selected.length}');
          } else {
            print("only one");
          }
          _checked = selected;
        }),
      ),

完整代码

/*
Name: Akshath Jain
Date: 3/15/19
Purpose: example app for the grouped buttons package
*/

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

void main() => runApp(GroupedButtonExample());

class GroupedButtonExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Grouped Buttons Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  List<String> _checked = []; //["A", "B"];
  String _picked = "Two";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Grouped Buttons Example"),
      ),
      body: _body(),
    );
    //
  }

  Widget _body() {
    return ListView(children: <Widget>[
      //--------------------
      //SIMPLE USAGE EXAMPLE
      //--------------------

      //BASIC CHECKBOXGROUP
      Container(
        padding: const EdgeInsets.only(left: 14.0, top: 14.0),
        child: Text(
          "Basic CheckboxGroup",
          style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20.0),
        ),
      ),

      CheckboxGroup(
        labels: <String>[
          "Sunday",
          "Monday",
          "Tuesday",
          "Wednesday",
          "Thursday",
          "Friday",
          "Saturday",
        ],
        disabled: ["Wednesday", "Friday"],
        checked: _checked,
        onChange: (bool isChecked, String label, int index) =>
            print("isChecked: $isChecked   label: $label  index: $index"),
        onSelected: (List selected) => setState(() {
          if (selected.length > 1) {
            selected.removeAt(0);
            print('selected length  ${selected.length}');
          } else {
            print("only one");
          }
          _checked = selected;
        }),
      ),

      //BASIC RADIOBUTTONGROUP
      Container(
        padding: const EdgeInsets.only(left: 14.0, top: 14.0),
        child: Text(
          "Basic RadioButtonGroup",
          style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20.0),
        ),
      ),

      RadioButtonGroup(
        labels: [
          "Option 1",
          "Option 2",
        ],
        disabled: ["Option 1"],
        onChange: (String label, int index) =>
            print("label: $label index: $index"),
        onSelected: (String label) => print(label),
      ),

      //--------------------
      //CUSTOM USAGE EXAMPLE
      //--------------------

      ///CUSTOM CHECKBOX GROUP
      Container(
        padding: const EdgeInsets.only(left: 14.0, top: 14.0, bottom: 14.0),
        child: Text(
          "Custom CheckboxGroup",
          style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20.0),
        ),
      ),

      CheckboxGroup(
        orientation: GroupedButtonsOrientation.HORIZONTAL,
        margin: const EdgeInsets.only(left: 12.0),
        onSelected: (List selected) => setState(() {
          _checked = selected;
        }),
        labels: <String>[
          "A",
          "B",
        ],
        checked: _checked,
        itemBuilder: (Checkbox cb, Text txt, int i) {
          return Column(
            children: <Widget>[
              Icon(Icons.polymer),
              cb,
              txt,
            ],
          );
        },
      ),

      ///CUSTOM RADIOBUTTON GROUP
      Container(
        padding: const EdgeInsets.only(left: 14.0, top: 14.0, bottom: 14.0),
        child: Text(
          "Custom RadioButtonGroup",
          style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20.0),
        ),
      ),

      RadioButtonGroup(
        orientation: GroupedButtonsOrientation.HORIZONTAL,
        margin: const EdgeInsets.only(left: 12.0),
        onSelected: (String selected) => setState(() {
          _picked = selected;
        }),
        labels: <String>[
          "One",
          "Two",
        ],
        picked: _picked,
        itemBuilder: (Radio rb, Text txt, int i) {
          return Column(
            children: <Widget>[
              Icon(Icons.public),
              rb,
              txt,
            ],
          );
        },
      ),
    ]);
  }
}

工作演示

enter image description here