flutter 使用复选框列表平铺-抖动选择单个复选框

uoifb46i  于 2022-12-24  发布在  Flutter
关注(0)|答案(3)|浏览(257)

我试图从复选框列表中选择一个或多个复选框,我发现最好的选择是使用checkBoxListTile小部件来实现这一点。
首先,我定义了一个列表,并按如下方式使用小部件:

List<String> _texts = ["google.com", "youtube.com", "yahoo.com", "gmail.com"];

      Expanded(
        child: ListView(
          children: _texts
              .map((text) => CheckboxListTile(
                    title: Text(text),
                    value: _isChecked,
                    onChanged: (val) {
                      setState(() {
                        _isChecked = val;
                      });
                    },
                  ))
              .toList(),
        ),
      ),

复选框显示良好,但每当我单击一个复选框时,所有复选框都被选中,我如何处理从列表中选择一个或多个复选框?
谢谢

bmp9r5qi

bmp9r5qi1#

尝试下面的代码,希望它对你有帮助,我已经尝试了其他方式

仅选中单个复选框:

您的列表:

List _texts = [
    {
      "value": false,
      "site": "google.com",
    },
    {
      "value": false,
      "site": "youtube.com",
    },
    {
      "value": false,
      "site": "yahoo.com",
    },
    {
      "value": false,
      "site": "gmail.com",
    },
  ];

您的小工具:

Padding(
        padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 64.0),
        child: Column(
          children: List.generate(
            _texts.length,
            (index) => CheckboxListTile(
              controlAffinity: ListTileControlAffinity.leading,
              contentPadding: EdgeInsets.zero,
              dense: true,
              title: Text(
                _texts[index]["site"],
                style: const TextStyle(
                  fontSize: 16.0,
                  color: Colors.black,
                ),
              ),
              value: _texts[index]["value"],
              onChanged: (value) {
                setState(() {
                  for (var element in _texts) {
                    element["value"] = false;
                  }
                  _texts[index]["value"] = value;
                });
              },
            ),
          ),
        ),
      ),

完整代码:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
          appBar: AppBar(
            title: Text("Flutter Single Checkbox Example"),
          ),
          body: SafeArea(
              child: Center(
            child: CheckboxWidget(),
          ))),
    );
  }
}

class CheckboxWidget extends StatefulWidget {
  @override
  CheckboxWidgetState createState() => new CheckboxWidgetState();
}

class CheckboxWidgetState extends State {
  List _texts = [
    {
      "value": false,
      "site": "google.com",
    },
    {
      "value": false,
      "site": "youtube.com",
    },
    {
      "value": false,
      "site": "yahoo.com",
    },
    {
      "value": false,
      "site": "gmail.com",
    },
  ];
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 64.0),
      child: Column(
        children: List.generate(
          _texts.length,
          (index) => CheckboxListTile(
            controlAffinity: ListTileControlAffinity.leading,
            contentPadding: EdgeInsets.zero,
            dense: true,
            title: Text(
              _texts[index]["site"],
              style: const TextStyle(
                fontSize: 16.0,
                color: Colors.black,
              ),
            ),
            value: _texts[index]["value"],
            onChanged: (value) {
              setState(() {
                for (var element in _texts) {
                  element["value"] = false;
                }
                _texts[index]["value"] = value;
              });
            },
          ),
        ),
      ),
    );
  }
}

结果屏幕-〉

多个复选框选择

    • 您的列表/Map**
Map<String, bool> values = {
    'google.com': false,
    'youtube.com': false,
    'yahoo.com': false,
    'gmail.com': false,
  };

您的职能:

var tmpArray = [];  
  getCheckboxItems() {
    values.forEach((key, value) {
      if (value == true) {
        tmpArray.add(key);
      }
    });

    print(tmpArray);
    tmpArray.clear();
  }

您的小工具:

Column(
      children: <Widget>[
          ListView(
            shrinkWrap: true,
            children: values.keys.map((String key) {
              return new CheckboxListTile(
                title: new Text(key),
                value: values[key],
                onChanged: (value) {
                  setState(() {
                    values[key] = value!;
                  });
                },
              );
            }).toList(),
          
        ),
        const SizedBox(
          height: 100,
        ),
        ElevatedButton(
          child: Text(
            " Checkbox Items ",
            style: TextStyle(fontSize: 18),
          ),
          onPressed: getCheckboxItems,
        ),
      ],
    )

完整示例

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
          appBar: AppBar(
            title: Text("Flutter Multiple Checkbox Example"),
          ),
          body: SafeArea(
              child: Center(
            child: CheckboxWidget(),
          ))),
    );
  }
}

class CheckboxWidget extends StatefulWidget {
  @override
  CheckboxWidgetState createState() => new CheckboxWidgetState();
}

class CheckboxWidgetState extends State {
  Map<String, bool> values = {
    'google.com': false,
    'youtube.com': false,
    'yahoo.com': false,
    'gmail.com': false,
  };

  var tmpArray = [];

  getCheckboxItems() {
    values.forEach((key, value) {
      if (value == true) {
        tmpArray.add(key);
      }
    });

    print(tmpArray);
    tmpArray.clear();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
          ListView(
            shrinkWrap: true,
            children: values.keys.map((String key) {
              return new CheckboxListTile(
                title: new Text(key),
                value: values[key],
                onChanged: (value) {
                  setState(() {
                    values[key] = value!;
                  });
                },
              );
            }).toList(),
          
        ),
        const SizedBox(
          height: 100,
        ),
        ElevatedButton(
          child: Text(
            " Checkbox Items ",
            style: TextStyle(fontSize: 18),
          ),
          onPressed: getCheckboxItems,
        ),
      ],
    );
  }
}

结果屏幕-〉

9lowa7mx

9lowa7mx2#

import 'package:flutter/material.dart';

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

/// This Widget is the main application widget.
class MyApp extends StatelessWidget {
  static const String _title = 'Flutter Code Sample';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: _title,
      home: CheckBoxExample(),
    );
  }
}

class CheckBoxExample extends StatefulWidget {
  const CheckBoxExample({Key? key}) : super(key: key);

  @override
  State<CheckBoxExample> createState() => _CheckBoxExampleState();
}

class _CheckBoxExampleState extends State<CheckBoxExample> {
  String selectedMonth = "";
  List checkListItems = [
    {
      "id": 0,
      "value": false,
      "monthName": "January",
    },
    {
      "id": 1,
      "value": false,
      "monthName": "Febuary",
    },
    {
      "id": 2,
      "value": false,
      "monthName": "March",
    },
    {
      "id": 3,
      "value": false,
      "monthName": "April",
    },
    {
      "id": 4,
      "value": false,
      "monthName": "May",
    },
    {
      "id": 5,
      "value": false,
      "monthName": "June",
    },
    {
      "id": 6,
      "value": false,
      "monthName": "July",
    },
    {
      "id": 7,
      "value": false,
      "monthName": "August",
    },
    {
      "id": 8,
      "value": false,
      "monthName": "September",
    },
    {
      "id": 9,
      "value": false,
      "monthName": "October",
    },
    {
      "id": 10,
      "value": false,
      "monthName": "November",
    },
    {
      "id": 11,
      "value": false,
      "monthName": "December",
    },
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 64.0),
        child: Column(
          children: [
            Text(
              selectedMonth,
              style: const TextStyle(
                fontSize: 20.0,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 85.0),
            Column(
              children: List.generate(
                checkListItems.length,
                (index) => CheckboxListTile(
                  controlAffinity: ListTileControlAffinity.leading,
                  contentPadding: EdgeInsets.zero,
                  dense: true,
                  title: Text(
                    checkListItems[index]["monthName"],
                    style: const TextStyle(
                      fontSize: 16.0,
                      color: Colors.black,
                    ),
                  ),
                  value: checkListItems[index]["value"],
                  onChanged: (value) {
                    setState(() {
                      for (var element in checkListItems) {
                        element["value"] = false;
                      }
                      checkListItems[index]["value"] = value;
                      selectedMonth ="${checkListItems[index]["id"]+1}, ${checkListItems[index]["monthName"]}";
                    });
                  },
                ),
              ),
            ),          
          ],
        ),
      ),
    );
  }
}

产出

amrnrhlw

amrnrhlw3#

CheckboxListTile中的value参数是小部件如何知道复选框是否被选中。当你给予所有的小部件相同的value时,所有的小部件的状态都会改变。你可以保留一个单独的列表来跟踪特定的复选框是否被选中。

相关问题