checkbox - 更新复选框并从 flutter 中的对话框返回值

标签 checkbox dart dialog flutter

我正在尝试将一些城市列表添加到带有复选框的对话框中,以便我需要实现对项目的多次点击。下面给出了我想要做的事情。

onPressed 从按钮调用 Rest Service 并在成功结果时显示一个对话框

void showCityDialog(BuildContext context) {
    SimpleDialog dialog = new SimpleDialog(
      title: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          new Text(
            "CITIES",
            style: TextStyle(fontSize: 18.0, color: Colors.black),
            textAlign: TextAlign.center,
          ),
          new RaisedButton(
            onPressed: () {print("clicked");},
            color: Color(0xFFfab82b),
            child: new Text(
              "Done",
              style: TextStyle(color: Colors.white),
            ),)],),
      children: <Widget>[
        Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            new Container(
              constraints: BoxConstraints(maxHeight: 500.0),
              child: ListView.builder(
                scrollDirection: Axis.vertical,
                itemCount: cityData.length,
                itemBuilder: (context, position) {
                  return new CheckboxListTile(
                    value: checkboxValueCity,
                    onChanged: (bool value) {
                      setState(() {
                        checkboxValueCity = value;
                      });
                    },
                    activeColor: Color(0xFFfab82b),
                    dense: true,
                    title: Text(
                      cityData[position].city_name,
                      style: TextStyle(fontSize: 16.0, color: Colors.black),
                    ),);},),),],)],);
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return dialog;
        });
  }

checkboxValueCity 是类中的 bool 变量,单击 chekboxListItem 我需要将复选框值更新为已选中和未选中。同时需要将该项目添加/删除到该类内的列表中。

但在我的代码中,复选框并没有在每次点击时引用,但是当我关闭该框并再次打开它时,复选框被选中。那么如何从磁贴中获得多次点击以及如何从对话框中返回列表?

最佳答案

您的对话框需要是 StatefulWidget (Flutter Github issue)。跟踪选择状态的成员变量需要在对话框类中。您可以使用回调来使用所选城市的 List 更新父类中的成员变量。在 SimpleDialogAlertDialog 中使用 ListView.builder 似乎也存在一些问题(在 Flutter Github 上搜索问题),所以我使用了一个普通的 Dialog.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Checkbox Dialog Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Checkbox Dialog Demo'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool checkboxValueCity = false;
  List<String> allCities = ['Alpha', 'Beta', 'Gamma'];
  List<String> selectedCities = [];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
          child: Icon(Icons.add),
          onPressed: () {
            showDialog(
                context: context,
                builder: (context) {
                  return _MyDialog(
                      cities: allCities,
                      selectedCities: selectedCities,
                      onSelectedCitiesListChanged: (cities) {
                        selectedCities = cities;
                        print(selectedCities);
                      });
                });
          }),
    );
  }
}

class _MyDialog extends StatefulWidget {
  _MyDialog({
    this.cities,
    this.selectedCities,
    this.onSelectedCitiesListChanged,
  });

  final List<String> cities;
  final List<String> selectedCities;
  final ValueChanged<List<String>> onSelectedCitiesListChanged;

  @override
  _MyDialogState createState() => _MyDialogState();
}

class _MyDialogState extends State<_MyDialog> {
  List<String> _tempSelectedCities = [];

  @override
  void initState() {
    _tempSelectedCities = widget.selectedCities;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Dialog(
      child: Column(
        children: <Widget>[
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Text(
                'CITIES',
                style: TextStyle(fontSize: 18.0, color: Colors.black),
                textAlign: TextAlign.center,
              ),
              RaisedButton(
                onPressed: () {
                  Navigator.pop(context);
                },
                color: Color(0xFFfab82b),
                child: Text(
                  'Done',
                  style: TextStyle(color: Colors.white),
                ),
              ),
            ],
          ),
          Expanded(
            child: ListView.builder(
                itemCount: widget.cities.length,
                itemBuilder: (BuildContext context, int index) {
                  final cityName = widget.cities[index];
                  return Container(
                    child: CheckboxListTile(
                        title: Text(cityName),
                        value: _tempSelectedCities.contains(cityName),
                        onChanged: (bool value) {
                          if (value) {
                            if (!_tempSelectedCities.contains(cityName)) {
                              setState(() {
                                _tempSelectedCities.add(cityName);
                              });
                            }
                          } else {
                            if (_tempSelectedCities.contains(cityName)) {
                              setState(() {
                                _tempSelectedCities.removeWhere(
                                    (String city) => city == cityName);
                              });
                            }
                          }
                          widget
                              .onSelectedCitiesListChanged(_tempSelectedCities);
                        }),
                  );
                }),
          ),
        ],
      ),
    );
  }
}

关于checkbox - 更新复选框并从 flutter 中的对话框返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52676334/

相关文章:

html - 从 Angular 2 typescript 中的 HTML 获取复选框值。

c# - 验证不使用模型时是否选中复选框

Flutter 在现有项目中构建 Web 不断失败

java - 当 ListView 只有几个项目时,如何使警报对话框显示 ListView 的所有项目?

php - 如果数据库中的值相同,则添加选中的复选框

javascript - 仅在 Dartium 中调试我的 Dart 编写的客户端 Web 应用程序是否足够?

flutter - Flutter:在容器底部放置分隔线吗?

dialog - JavaFX8 : How do I set the initially focused control in a Stage?

android - 自定义对话框中EditText的值

extjs - 修复了 EXTJS 面板中的复选框列