如何 select 从 Flutter 中的复选框列表磁贴中仅选择一个复选框并在文本字段中显示 selected 项目

How to select only one checkbox from Checkbox List tile in Flutter and show selected item in textField

这里有一个显示火车站底部 sheet 的文本字段 我怎么能 select 只有一个复选框并在文本字段中显示 selected 这是代码 谢谢提前,如果你教我如何在复选框列表的文本字段中按名称搜索,我将不胜感激

 Scaffold(
            backgroundColor: Colors.grey[300],
            appBar: AppBar(
              leading: IconButton(
                icon: Icon(Icons.arrow_back),
                onPressed: () {
                  Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (context) => ticketbookinghomepage()));
                },
              ),
              backgroundColor: Color(0xff240e8b),
              title: Text('Search By Station'),
              centerTitle: true,
            ),
            body: Container(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Container(
                      padding: EdgeInsets.all(10),
                      child: Column(
                        children: [
                          Text('Departure Station'),
                          Container(
                              padding: EdgeInsets.all(10),
                              decoration: BoxDecoration(
                                color: Colors.white,
                                borderRadius: BorderRadius.circular(16),
                              ),
                              child: TextField(
                                controller: startController,
                                autocorrect: true,
                                decoration: InputDecoration(
                                    labelText: '-Select Station',
                                    floatingLabelBehavior:
                                        FloatingLabelBehavior.never,
                                    filled: true,
                                    fillColor: Colors.white,
                                    suffixIcon: InkWell(
                                      onTap: () {
                                        showSourceBottomSheet(context);
                                      },
                                      child: Icon(
                                        Icons.arrow_drop_down_circle_outlined,
                                        color: Colors.black,
                                      ),
                                    ),
                                    border: OutlineInputBorder(
                                        borderRadius: BorderRadius.all(
                                            Radius.circular(30)))),
                              ))
                        ],
                      )),
                  SizedBox(height: 12),
                  IconButton(
                    icon: Icon(Icons.wifi_protected_setup_rounded),
                    color: Colors.black,
                    onPressed: () {},
                  ),
                  SizedBox(height: 12),
                  Container(
                      padding: EdgeInsets.all(10),
                      child: Column(
                        children: [
                          Text('ِِِArrival Station'),
                          Container(
                              padding: EdgeInsets.all(10),
                              decoration: BoxDecoration(
                                color: Colors.white,
                                borderRadius: BorderRadius.circular(16),
                              ),
                              child: TextField(
                                controller: arriveController,
                                autocorrect: true,
                                decoration: InputDecoration(
                                    labelText: '-Select Station',
                                    floatingLabelBehavior:
                                        FloatingLabelBehavior.never,
                                    filled: true,
                                    fillColor: Colors.white,
                                    suffixIcon: InkWell(
                                      onTap: () {
                                        showDestinationBottomSheet(context);
                                      },
                                      child: Icon(
                                        Icons.arrow_drop_down_circle_outlined,
                                        color: Colors.black,
                                      ),
                                    ),
                                    border: OutlineInputBorder(
                                        borderRadius: BorderRadius.all(
                                            Radius.circular(30)))),
                              ))
                        ],
                      )),
                  SizedBox(
                    height: 20,
                  ),
                  Container(
                    child: SizedBox(
                      height: 80,
                      width: 170,
                      child: ElevatedButton(
                        style: ButtonStyle(
                            backgroundColor:
                                MaterialStateProperty.all(Colors.amberAccent),
                            padding:
                                MaterialStateProperty.all(EdgeInsets.all(15)),
                            shape: MaterialStateProperty.all(
                                RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(25)))),
                        onPressed: () {},
                        child: Icon(
                          Icons.train,
                          color: Colors.deepPurple,
                        ),
                      ),
                    ),
                  ),
                  SizedBox(
                    height: 15,
                  ),
                  
                ],
              ),
            ),
          )  

底部Sheet代码

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class sourceBottomSheet extends StatefulWidget {
  const sourceBottomSheet({Key? key}) : super(key: key);

  @override
  State<sourceBottomSheet> createState() => _sourceBottomSheetState();
}
bool? checkBox1=false;
bool? checkBox2=false;
bool? checkBox3=false;
bool? checkBox4=false;
bool? checkBox5=false;
bool? checkBox6=false;
bool? checkBox7=false;
bool? checkBox8=false;
class _sourceBottomSheetState extends State<sourceBottomSheet> {
  @override
  Widget build(BuildContext context) {
    return StatefulBuilder(builder: (context, setState) {
      return Container(
        color: Colors.grey[600],
        child: Container(
          decoration: BoxDecoration(
            color:Colors.white,
            borderRadius: BorderRadius.only(topLeft: Radius.circular(30),topRight: Radius.circular(30))
          ),
          child: SingleChildScrollView(
            child: Column(
              children: [
                CheckboxListTile(
                    activeColor:Color(0xff070000),
                    checkColor:Color(0xffffffff) ,
                    title: Text('Cairo'),
                    value: checkBox1, onChanged: (v) {
                  setState(() {
                    checkBox1 = v;
                  });
                }),
                CheckboxListTile(
                    activeColor:Color(0xff070000),
                    checkColor:Color(0xffffffff) ,
                    title: Text('Alexandria')
                    , value: checkBox2, onChanged: (v) {
                  setState(() {
                    checkBox2 = v;
                  });
                }),
                CheckboxListTile(
                    activeColor:Color(0xff070000),
                    checkColor:Color(0xffffffff) ,
                    title: Text('Mansoura'),
                    value: checkBox3, onChanged: (v) {
                  setState(() {
                    checkBox3 = v;
                  });
                }),
                CheckboxListTile(
                    activeColor:Color(0xff070000),
                    checkColor:Color(0xffffffff) ,
                    title: Text('Shoubra Elkhema'),
                    value: checkBox4, onChanged: (v) {
                  setState(() {
                    checkBox4 = v;
                  });
                }),
                CheckboxListTile(
                    activeColor:Color(0xff070000),
                    checkColor:Color(0xffffffff) ,
                    title: Text('Banha'),
                    value: checkBox5, onChanged: (v) {
                  setState(() {
                    checkBox5 = v;
                  });
                }),
                CheckboxListTile(
                    activeColor:Color(0xff070000),
                    checkColor:Color(0xffffffff) ,
                    title: Text('Louxor'),
                    value: checkBox7, onChanged: (v) {
                  setState(() {
                    checkBox7 = v;
                  });

                }
                ),
                CheckboxListTile(
                    activeColor:Color(0xff070000),
                    checkColor:Color(0xffffffff) ,
                    title: Text('Port Said'),
                    value: checkBox8, onChanged: (v) {
                  setState(() {
                    checkBox8 = v;
                  });
                }),
                ListTile(
                    title:Text('Submit',textAlign: TextAlign.center,),
                    onTap:(){

                      Navigator.pop(context);
                    }),
              ],
            ),
          ),
        ),
      );
    }
    );
  }
}     

主页错误 Home class error

show bottom sheet error he want context and builder

您可以按照 code-commnet 中描述的代码段进行操作,并针对测试和用例进行了简化。

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

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

class _HomeState extends State<Home> {
  Future<List<String?>> showBottomSheet() async {
    Map<String, bool> items = {
      'Cairo': false,
      'Alexandria': false,
      'Mansoura': false,
    };

    await showModalBottomSheet(
      context: context,
      builder: (c) => StatefulBuilder(
        builder: (context, setStateSB) {
          return Container(
            color: Colors.grey[600],
            child: Container(
              decoration: const BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(30),
                      topRight: Radius.circular(30))),
              child: SingleChildScrollView(
                child: Column(
                  children: [
                    ...items.keys.map(
                      (key) => CheckboxListTile(
                          activeColor: Color(0xff070000),
                          checkColor: Color(0xffffffff),
                          title: Text(key),
                          value: items[key],
                          onChanged: (v) {
                            setStateSB(() {
                              items[key] = v ?? false;
                            });
                          }),
                    ),
                    ListTile(
                        title: Text(
                          'Submit',
                          textAlign: TextAlign.center,
                        ),
                        onTap: () {
                          Navigator.pop(context);
                        }),
                  ],
                ),
              ),
            ),
          );
        },
      ),
    );

    /// we will store selected items
    List<String> result = [];

    ///finding the selected items
    items.entries.map(
      (element) {
        if (element.value == true) result.add(element.key);
      },
    ).toList();

    return result;
  }

  final TextEditingController controller = TextEditingController();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[300],
      body: Container(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            Container(
                padding: EdgeInsets.all(10),
                child: Column(
                  children: [
                    Container(
                        padding: EdgeInsets.all(10),
                        decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(16),
                        ),
                        child: TextField(
                          controller: controller,
                          autocorrect: true,
                          decoration: InputDecoration(
                              labelText: '-Select Station',
                              floatingLabelBehavior:
                                  FloatingLabelBehavior.never,
                              filled: true,
                              fillColor: Colors.white,
                              suffixIcon: InkWell(
                                onTap: () async {
                                  final result = await showBottomSheet();

                                  print(result);

                                  final text = result.toString();

                                  ///removing start and end brackets
                                  controller.text =
                                      text.substring(1, text.length - 1);
                                },
                                child: Icon(
                                  Icons.arrow_drop_down_circle_outlined,
                                  color: Colors.black,
                                ),
                              ),
                              border: OutlineInputBorder(
                                  borderRadius:
                                      BorderRadius.all(Radius.circular(30)))),
                        ))
                  ],
                )),
          ],
        ),
      ),
    );
  }
}

所以我使用了 roadio 列表而不是复选框列表并且使用起来更容易这里是代码:

class sourceBottomSheet extends StatefulWidget {
sourceBottomSheet(TextEditingController? _cont) {
  controller = _cont;
}

String get value => valuet;

@override
State<sourceBottomSheet> createState() => _sourceBottomSheetState(controller);
}

String valuet = "";
Object? st;

void setval(String _value) {
controller?.text = _value;
}

class _sourceBottomSheetState extends State<sourceBottomSheet> {
_sourceBottomSheetState(TextEditingController? cont) {
  // con?.text = valuet;
}

@override
Widget build(BuildContext context) {
  return StatefulBuilder(builder: (context, setState) {
    return Container(
      color: Colors.grey[600],
      child: Container(
        decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.only(
                topLeft: Radius.circular(30), topRight: Radius.circular(30))),
        child: SingleChildScrollView(
          child: Column(
            children: [
              RadioListTile(
                value: 1,
                groupValue: st,
                title: Text("Cairo"),
                // subtitle: Text("Radio 1 Subtitle"),
                onChanged: (val) {
                  setval("Cairo");
                  setState(() {
                    if (st != val) {
                      st = val;
                    }
                    //else{st=val;}
                  });
                },
                //  selected:true,
                activeColor: Colors.red,
              ),
              RadioListTile(
                value: 2,
                groupValue: st,
                title: Text("Banha"),
                // subtitle: Text("Radio 1 Subtitle"),
                onChanged: (val) {
                  setval("Banha");
                  print("st pressed $st");
                  setState(() {
                    if (st != val) {
                      st = val;
                    }
                    //    else{st=0;}
                  });
                },
                //  selected:true,
                activeColor: Colors.red,
              ),
              RadioListTile(
                value: 3,
                groupValue: st,
                title: Text("Aleaxandria"),
                // subtitle: Text("Radio 1 Subtitle"),
                onChanged: (val) {
                  print("Radio Tile pressed $val");
                  print("st pressed $st");
                  setval("Aleaxandria");
                  setState(() {
                    if (st != val) {
                      st = val;
                    }
                    //    else{st=0;}
                  });
                },
                //  selected:true,
                activeColor: Colors.red,
              ),
              RadioListTile(
                value: 4,
                groupValue: st,
                title: Text("Matrouh"),
                // subtitle: Text("Radio 1 Subtitle"),
                onChanged: (val) {
                  print("Radio Tile pressed $val");
                  print("st pressed $st");
                  setval("Matrouh");

                  setState(() {
                    if (st != val) {
                      st = val;
                    }
                    //    else{st=0;}
                  });
                },
                //  selected:true,
                activeColor: Colors.red,
              ),
              RadioListTile(
                value: 5,
                groupValue: st,
                title: Text("Port Said"),
                // subtitle: Text("Radio 1 Subtitle"),
                onChanged: (val) {
                  print("Radio Tile pressed $val");
                  print("st pressed $st");
                  setval("Port Said");

                  setState(() {
                    if (st != val) {
                      st = val;
                    }
                    //    else{st=0;}
                  });
                },
                //  selected:true,
                activeColor: Colors.red,
              ),
              RadioListTile(
                value: 6,
                groupValue: st,
                title: Text("Mansoura"),
                // subtitle: Text("Radio 1 Subtitle"),
                onChanged: (val) {
                  print("Radio Tile pressed $val");
                  print("st pressed $st");
                  setval("Mansoura");

                  setState(() {
                    if (st != val) {
                      st = val;
                    }
                    //    else{st=0;}
                  });
                },
                //  selected:true,
                activeColor: Colors.red,
              ),
              RadioListTile(
                value: 7,
                groupValue: st,
                title: Text("Louxor"),
                // subtitle: Text("Radio 1 Subtitle"),
                onChanged: (val) {
                  print("Radio Tile pressed $val");
                  print("st pressed $st");
                  setval("Louxor");

                  setState(() {
                    if (st != val) {
                      st = val;
                    }
                    //    else{st=0;}
                  });
                },
                //  selected:true,
                activeColor: Colors.red,
              ),
              ListTile(
                  title: Text(
                    'Submit',
                    textAlign: TextAlign.center,
                  ),
                  onTap: () {
                    Navigator.pop(context);
                  }),
            ],
          ),
        ),
      ),
    );
  });
}
}```

底层源码Sheet函数代码

sourceBottomSheet bs = sourceBottomSheet(_cont);
//bs.sourceBottomSheet1(_cont);
showModalBottomSheet(
    context: context,
    builder: (buildContext) {
      return bs;
      //    return sourceBottomSheet();
    });
} ```