如何在 flutter 中将复选框标记为已选中?

How to mark a checkbox as selected in flutter?

我有一组复选框,我只需要突出显示 selected 复选框。但是,当我 select 一个时,它会将所有复选框突出显示为 selected。我该如何纠正这个问题?这是我到目前为止所做的:

bool isSelected = false;
var estateRooms = [];

@override
void didChangeDependencies() {
  final EstateSearch estate =
    ModalRoute.of(context) !.settings.arguments as EstateSearch;

  estateRooms = estate.rooms!;

  super.didChangeDependencies();
}

Expanded(
  child: Column(
    children: [
      for (var item in estateRooms)
        CheckboxListTile(
          title: Text('${item.name}'.toUpperCase()),
          value: isSelected,
          onChanged: (value) {
            setState(() {
              isSelected = value!;
              _roomController.text = '${item.id}';
              print('${_roomController.text}');
            });
          },
          controlAffinity: ListTileControlAffinity.leading,
        ),
    ],
  ),
),

在下面的屏幕截图中,我 select 编辑了第一个复选框,但它将两个复选框都标记为 select 编辑了。

您正在使用单个布尔变量 isSelected,您需要制作一个大小与 estateRooms 相同的布尔变量列表,并将列表中的每一项分配给不同的 [=12] =].

很多方法可以解决 this.you 不仅需要参考复选框状态 name.you 使用单个 ischecked field.to 解决你可以在你的 estateRooms 模型中添加 ischecked 字段 class.or 创建ischecked 数组并根据索引更新值

看这一段

var estateRooms = [
  EstateRoom(false, "Double Suite"),
  EstateRoom(false, "Family suite")
];
class _HomeState extends State<Home> {
  @override
  Widget build(BuildContext context) {
    // bool isSelected = false;
    // var estateRooms = [];

    @override
    void didChangeDependencies() {
      // final EstateSearch estate =
      //     ModalRoute.of(context)!.settings.arguments as EstateSearch;
      //
      // estateRooms = estate.rooms!;

      super.didChangeDependencies();
    }

    var isSelected = [false, false];

    return Column(
      children: [
        for (var item in estateRooms)
          CheckboxListTile(
            title: Text('${item.name}'.toUpperCase()),
            value: item.isSelected,
            onChanged: (value) {
              setState(() {
                item.isSelected = value!;
                // _roomController.text = '${item.id}';
                // print('${_roomController.text}');
              });
            },
            controlAffinity: ListTileControlAffinity.leading,
          ),
      ],
    );
  }
}

class EstateRoom {
  bool isSelected;
  String name;

  EstateRoom(this.isSelected, this.name);
}

var isSelected = [false, false];
var estateRooms = ["Double Suite", "Family suite"];

class _HomeState extends State<Home> {
  @override
  Widget build(BuildContext context) {
    // bool isSelected = false;
    // var estateRooms = [];

    @override
    void didChangeDependencies() {
      // final EstateSearch estate =
      //     ModalRoute.of(context)!.settings.arguments as EstateSearch;
      //
      // estateRooms = estate.rooms!;

      super.didChangeDependencies();
    }

 

    return Column(
      children: [
        for (var item in estateRooms)
          CheckboxListTile(
            title: Text('${item}'.toUpperCase()),
            value: isSelected[estateRooms.indexOf(item)],
            onChanged: (value) {
              var indexOf = estateRooms.indexOf(item);
              setState(() {
                isSelected[indexOf] = value!;
                // _roomController.text = '${item.id}';
                // print('${_roomController.text}');
              });
            },
            controlAffinity: ListTileControlAffinity.leading,
          ),
      ],
    );
  }
}

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

  @override
  State<Home> createState() => _HomeState();
}

var estateRooms = [EstateRoom("Double Suite"), EstateRoom("Family suite")];
// var isSelected = [false, false];
// var estateRooms = ["Double Suite", "Family suite"];

class _HomeState extends State<Home> {
  @override
  Widget build(BuildContext context) {
    // bool isSelected = false;
    // var estateRooms = [];

    @override
    void didChangeDependencies() {
      // final EstateSearch estate =
      //     ModalRoute.of(context)!.settings.arguments as EstateSearch;
      //
      // estateRooms = estate.rooms!;

      super.didChangeDependencies();
    }

    return Column(
      children: [
        for (var item in estateRooms)
          CheckboxListTile(
            title: Text('${item.name}'.toUpperCase()),
            value: item.isSelected,
            onChanged: (value) {
              var indexOf = estateRooms.indexOf(item);
              setState(() {
                item.isSelected = value!;
                // _roomController.text = '${item.id}';
                // print('${_roomController.text}');
              });
            },
            controlAffinity: ListTileControlAffinity.leading,
          ),
      ],
    );
  }
}

class EstateRoom {
  bool isSelected = false;
  String name;

  EstateRoom(this.name, {this.isSelected = false});
}

示例代码 Dartpad live check here

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

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // home: MyHomePage(title: 'Flutter Demo Home Page'),
      home: Scaffold(appBar: AppBar(), body: Home()),
    );
  }
}

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

  @override
  State<Home> createState() => _HomeState();
}
var estateRooms = [
  EstateRoom(false, "Double Suite"),
  EstateRoom(false, "Family suite")
];
class _HomeState extends State<Home> {
  @override
  Widget build(BuildContext context) {
    // bool isSelected = false;
    // var estateRooms = [];

    @override
    void didChangeDependencies() {
      // final EstateSearch estate =
      //     ModalRoute.of(context)!.settings.arguments as EstateSearch;
      //
      // estateRooms = estate.rooms!;

      super.didChangeDependencies();
    }

    var isSelected = [false, false];

    return Column(
      children: [
        for (var item in estateRooms)
          CheckboxListTile(
            title: Text('${item.name}'.toUpperCase()),
            value: item.isSelected,
            onChanged: (value) {
              setState(() {
                item.isSelected = value!;
                // _roomController.text = '${item.id}';
                // print('${_roomController.text}');
              });
            },
            controlAffinity: ListTileControlAffinity.leading,
          ),
      ],
    );
  }
}

class EstateRoom {
  bool isSelected;
  String name;

  EstateRoom(this.isSelected, this.name);
}