在Flutter中动态创建的复选框不会更改单击状态 [英] Dynamically created checkbox in flutter not changing the state on clicked

查看:537
本文介绍了在Flutter中动态创建的复选框不会更改单击状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每次按下按钮时,我都会创建一个复选框字段。但是生成的复选框在按下时不会更改状态,而是生成的下一个复选框带有已更改的状态。

I am creating a checkbox field every time i press a button. but the generated checkbox is not changing the state when pressed, instead the next checkbox which is generated comes with the changed state.

我已附加了有关其当前工作方式的视频( https://imgur.com/a/75vE5cj

I have attached the video of how it is working currently (https://imgur.com/a/75vE5cj )

我的整个代码是这样的:

my entire code goes like this :

class ToDoNotes extends StatelessWidget {
 @override
  Widget build(BuildContext context) {
  SizeConfig().init(context);
  return new MaterialApp(
  title: 'notes',
  theme: new ThemeData(
    primarySwatch: Colors.green,
  ),
  home: new T_notes(),
); }}

class T_notes extends StatefulWidget {
 static String tag = 'T_notes';
@override
_T_notesState createState() => new _T_notesState();
}

这是我用于动态创建复选框的代码。

this is my code for creating checkbox dynamically.

class _T_notesState extends State<T_notes> {
bool rememberMe = false;
 void _onRememberMeChanged(bool newValue) => setState(() {
 rememberMe = newValue;
 });
List<Widget> _children = [];
int _count = 0;
String input;
int i=0;
void _add() {
_children = List.from(_children)
  ..add(
      CheckboxListTile(
        value: rememberMe,
        onChanged: _onRememberMeChanged,
        title: new Text(input,style: TextStyle(color: Colors.black)),
        controlAffinity: ListTileControlAffinity.leading,
        activeColor: Colors.black,
      )
   );
 setState(() {
  ++_count;
});
i++;
}

在小部件内部的build()里面,我有如下的动态小部件:

inside the widget build() inside the body i have the dynamic widget as:

@override
Widget build(BuildContext context) {
return new Scaffold(
  resizeToAvoidBottomPadding: false,
     body: ListView(
    padding: EdgeInsets.all(28.0),
      children: <Widget>[
        SizedBox(height: 30),
        new Row(
          children: <Widget>[
            SizedBox(width:0.2),
            new Container(
              width:200,
              child: new TextField(
                textAlign: TextAlign.left,
                decoration: InputDecoration(
                  border: OutlineInputBorder(borderRadius: BorderRadius.circular(138.0)),
                  hintText: 'Enter the text',
                ),
                onChanged: (val) {
                  input = val;
                  }
              ),
            ),

            SizedBox(width:10),
             new Container(
          width: 80,
          child:new Material(
            borderRadius: BorderRadius.circular(30.5),
            shadowColor: Colors.lightBlueAccent.shade100,
            elevation: 1.0,
            child: new MaterialButton(
              onPressed: () {
                _add();
                },
               child: Text('ADD', style: TextStyle(color: Colors.lightGreen,fontSize: 15)),
             ),
           ),
         ),
          ],
         ),
         new Container(
          height: 390,
          child: ListView(children: _children),
         ),
        ],
      ) ,
    );
  }

我希望复选框字段在单击时可以正确更改状态。

I want the checkbox field to change the state properly on clicked.

推荐答案

好吧,这里的事情是,您需要为每个CheckboxListTile建立一个模型,以保留每个CheckboxListTiles的状态。

Ok the thing here is that you need to have a model for each CheckboxListTile to preserve the state of each of the CheckboxListTiles.

这将是模型:

class ListTileModel {
  bool enabled;
  String text;

  ListTileModel(this.enabled,this.text);
}

然后,当用户点击图块时,只需更新该特定行的状态。您现在拥有的是所有图块的基本状态。因此,与其拥有一组小部件,不如拥有代表每一行的一系列模型。最后,使用map函数构建所有项目

Then, when a user taps a Tile, just update the state of that particular row. What you have now is a general state for all your Tiles. So instead of having an array of widgets, have an array of models representing each row. And finally, use the a map function to build all your items

class _T_notesState extends State<T_notes> {
  bool rememberMe = false;

  List<ListTileModel> _items = [];

  String input;
  int i = 0;

  void _add() {
    _items.add(ListTileModel(false,input));
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      resizeToAvoidBottomPadding: false,
      body: ListView(
        padding: EdgeInsets.all(28.0),
        children: <Widget>[
          SizedBox(height: 30),
          new Row(
            children: <Widget>[
              SizedBox(width: 0.2),
              new Container(
                width: 200,
                child: new TextField(
                    textAlign: TextAlign.left,
                    decoration: InputDecoration(
                      border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(138.0)),
                      hintText: 'Enter the text',
                    ),
                    onChanged: (val) {
                      input = val;
                    }),
              ),
              SizedBox(width: 10),
              new Container(
                width: 80,
                child: new Material(
                  borderRadius: BorderRadius.circular(30.5),
                  shadowColor: Colors.lightBlueAccent.shade100,
                  elevation: 1.0,
                  child: new MaterialButton(
                    onPressed: () {
                      _add();
                    },
                    child: Text('ADD',
                        style:
                            TextStyle(color: Colors.lightGreen, fontSize: 15)),
                  ),
                ),
              ),
            ],
          ),
          new Container(
            height: 390,
            child: ListView(
                children: _items
                    .map((item) => CheckboxListTile(
                          value: item.enabled,
                          onChanged: (enabled) {
                            item.enabled = enabled;
                            setState(() {});
                          },
                          title: new Text(item.text,
                              style: TextStyle(color: Colors.black)),
                          controlAffinity: ListTileControlAffinity.leading,
                          activeColor: Colors.black,
                        ))
                    .toList()),
          ),
        ],
      ),
    );
  }
}

这篇关于在Flutter中动态创建的复选框不会更改单击状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆