Problem switch values in ListView flutter

谁都会走 提交于 2021-01-27 10:34:03

问题


I create a Switch widget in ListView for each element. When i click on switch, the value change for all elements. I check in flutter docs, dart docs... I think, i don't recup the element position in onChanged method.

But how do ?

My value isSwitched changed when i clicked. I recup the lignes when i cliked thanks to : snapshot.data[index].name

Theme screen :

class _ThemePage extends State<ThemePage> {
  bool isSwitched = false;
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: Text("Blackbox"),
        leading: Image.asset(
          'assets/img/logo_ineat.png',
          fit: BoxFit.contain,
          height: 32,
        ),
      ),
      body: new Center(
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: <Widget>[
            new Container(
                margin: EdgeInsets.only(top: 10.0, bottom: 10.0),
                child: new Text('Sélection du profil',
                    style: new TextStyle(
                        fontSize: 24, fontWeight: FontWeight.bold)),
                alignment: Alignment.topCenter),
            new Flexible(
              child: new Container(
                child: new FutureBuilder<List<t.Theme>>(
                    future: t.Theme().getThemes(),
                    builder: (BuildContext context, AsyncSnapshot snapshot) {
                      if (snapshot.hasData) {
                        if (snapshot.data != null) {
                          return new Column(
                            children: <Widget>[
                              new Expanded(
                                child: new ListView.builder(
                                  itemCount: snapshot.data.length,
                                  itemBuilder: (BuildContext context, index) {
                                    return ListTile(
                                      title:
                                          new Text(snapshot.data[index].name),
                                          trailing: new Switch(
                                            value: isSwitched,
                                            activeColor: Colors.pink,
                                            activeTrackColor: Colors.pinkAccent,
                                            onChanged: (value){
                                              setState(() {
                                               isSwitched = value; 
                                               if(value==true) {
                                                 print(snapshot.data[index].name);
                                               }
                                              });
                                            },
                                          ),
                                    );
                                  },
                                ),
                              ),
                            ],
                          );
                        }
                      } else {
                        new Text("Loading...");
                        return new CircularProgressIndicator();
                      }
                    }),
              ),
            ),
            new Container(
              margin: EdgeInsets.only(right: 10.0),
              child: new RaisedButton.icon(
                /*onPressed: () {
                  Navigator.pushReplacement(context,
                      MaterialPageRoute(builder: (context) => Technologies()));
                },*/
                label: Text('Suivant'),
                icon: Icon(Icons.navigate_next),
              ),
              alignment: Alignment.bottomRight,
            ),
          ],
        ),
      ),
    );
  }
}


回答1:


you are controlling switched value with single property isSwitched

you can

  • create another stateful widget put your switch logic there (and if you want to read the value use a callback ) (cleaner)
  • create a list of bool instead of single property

your code with first solution:


class YourListViewItem extends StatefulWidget {

  final String title;

  const YourListViewItem({Key key, this.title}) : super(key: key);

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

class _YourListViewItemState extends State<YourListViewItem> {

  bool isSwitched = false;

  @override
  Widget build(BuildContext context) {
    return ListTile(
      title:
      new Text(widget.title),
      trailing: new Switch(
        value: isSwitched,
        activeColor: Colors.pink,
        activeTrackColor: Colors.pinkAccent,
        onChanged: (value){
          setState(() {
            isSwitched = value;
          });
        },
      ),
    );
  }
}


class _ThemePage extends State<ThemePage> {
  bool isSwitched = false;
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: Text("Blackbox"),
        leading: Image.asset(
          'assets/img/logo_ineat.png',
          fit: BoxFit.contain,
          height: 32,
        ),
      ),
      body: new Center(
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: <Widget>[
            new Container(
                margin: EdgeInsets.only(top: 10.0, bottom: 10.0),
                child: new Text('Sélection du profil',
                    style: new TextStyle(
                        fontSize: 24, fontWeight: FontWeight.bold)),
                alignment: Alignment.topCenter),
            new Flexible(
              child: new Container(
                child: new FutureBuilder<List<t.Theme>>(
                    future: t.Theme().getThemes(),
                    builder: (BuildContext context, AsyncSnapshot snapshot) {
                      if (snapshot.hasData) {
                        if (snapshot.data != null) {
                          return new Column(
                            children: <Widget>[
                              new Expanded(
                                child: new ListView.builder(
                                  itemCount: snapshot.data.length,
                                  itemBuilder: (BuildContext context, index) {
                                    return YourListViewItem(title: snapshot.data[index].name);
                                  },
                                ),
                              ),
                            ],
                          );
                        }
                      } else {
                        new Text("Loading...");
                        return new CircularProgressIndicator();
                      }
                    }),
              ),
            ),
            new Container(
              margin: EdgeInsets.only(right: 10.0),
              child: new RaisedButton.icon(
                /*onPressed: () {
                  Navigator.pushReplacement(context,
                      MaterialPageRoute(builder: (context) => Technologies()));
                },*/
                label: Text('Suivant'),
                icon: Icon(Icons.navigate_next),
              ),
              alignment: Alignment.bottomRight,
            ),
          ],
        ),
      ),
    );
  }
}




来源:https://stackoverflow.com/questions/57994179/problem-switch-values-in-listview-flutter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!