dart - Flutter: `onPressed` 作用于 ListView 中的所有 `IconButton`

标签 dart flutter

我想在按下后更改每个图标的颜色。但是 Expandable Container 中的所有图标在按下其中一个后都会发生变化。

class _ExpandableListViewState extends State<ExpandableListView> {
  bool expandFlag = false;
  Color _iconColor = Colors.white;

  @override
  Widget build(BuildContext context) {
    return new Container(
      margin: new EdgeInsets.symmetric(vertical: 1.0),
      child: new Column(
        children: <Widget>[
          new Container(
               .
               .
               .
               ),
          new ExpandableContainer(              
              expanded: expandFlag,
              expandedHeight: ...              
              child: new ListView.builder(
                itemBuilder: (BuildContext context, int index) {
                  return new Container(
                    decoration:
                        new BoxDecoration(border: new Border.all(width: 1.0, color: Colors.grey), color: Colors.black),                        
                     child: new ListTile(
                       title: ...

                       leading: new IconButton(
                        icon: Icon(Icons.star, color: _iconColor),
                        onPressed: () {
                          setState(() {                           
                           _iconColor = _iconColor == Colors.white ? Colors.yellow : Colors.white;                           
                          });
                        },
                      ),                                            
                      subtitle: ...                                                 
                  ), 
                  );
                },
                itemCount: ...,
              ))
        ],
      ),
    );
  }
}

class ExpandableContainer extends StatelessWidget {
  final bool expanded;
  final double expandedHeight;
  final Widget child;

  ExpandableContainer({
    @required this.child,
    this.expandedHeight,
    this.expanded = true,
  });

  @override
  Widget build(BuildContext context) {
.
.
.
}

完整代码:

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

void main() {
  runApp(new MaterialApp(home: new Home()));
}

class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      backgroundColor: Colors.grey,
      appBar: new AppBar(
        title: new Text("Expandable List", style: TextStyle(color: Colors.black)),
        backgroundColor: Colors.lightGreen,
      ),
      body: new ListView.builder(
        itemBuilder: (BuildContext context, int index) {
          return new ExpandableListView(title: broadcast[index].title, ind: index);
        },
        itemCount: broadcast.length,
      ),
    );
  }
}

class ExpandableListView extends StatefulWidget {
  final String title;
  final int ind;

  const ExpandableListView({this.title, this.ind});

  @override
  _ExpandableListViewState createState() => new _ExpandableListViewState();
}

class _ExpandableListViewState extends State<ExpandableListView> {
  bool expandFlag = false;
  Color _iconColor = Colors.white;

  @override
  Widget build(BuildContext context) {
    return new Container(
      margin: new EdgeInsets.symmetric(vertical: 1.0),
      child: new Column(
        children: <Widget>[
          new Container(
            color: Colors.blue[300],
            padding: new EdgeInsets.symmetric(horizontal: 5.0),
            child: new Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                new IconButton(
                    icon: new Container(
                      height: 50.0,
                      width: 50.0,
                      decoration: new BoxDecoration(
                        color: Colors.deepOrange,
                        shape: BoxShape.circle,
                      ),
                      child: new Center(
                        child: new Icon(
                          expandFlag ? Icons.keyboard_arrow_up : Icons.keyboard_arrow_down,
                          color: Colors.white,
                          size: 30.0,
                        ),
                      ),
                    ),
                    onPressed: () {
                      setState(() {
                        expandFlag = !expandFlag;
                      });
                    }),
                new Text(
                  widget.title,
                  style: new TextStyle(fontWeight: FontWeight.bold,fontSize: 20.0, color: Colors.black87),
                )
              ],
            ),
          ),
          new ExpandableContainer(              
              expanded: expandFlag,
              expandedHeight: 90.0 * (broadcast[widget.ind].contents.length < 4 ? broadcast[widget.ind].contents.length : 4), // + (0.0 ?: 29.0),              
              child: new ListView.builder(
                itemBuilder: (BuildContext context, int index) {
                  return new Container(
                    decoration:
                        new BoxDecoration(border: new Border.all(width: 1.0, color: Colors.grey), color: Colors.black),                        
                     child: new ListTile(
                      title: new Text(
                        broadcast[widget.ind].contents[index],
                        style: new TextStyle(fontWeight: FontWeight.bold, color: Colors.lightGreen),
                        textAlign: TextAlign.right,
                      ),
                       leading: new IconButton(
                        icon: Icon(Icons.star, color: _iconColor),
                        onPressed: () {
                          setState(() {                           
                           _iconColor = _iconColor == Colors.white ? Colors.yellow : Colors.white;                           
                          });
                        },
                      ),                                            
                      subtitle: new Text ('${broadcast[widget.ind].team[index]}\n${broadcast[widget.ind].time[index]}          ${broadcast[widget.ind].channel[index]}',
                      textAlign: TextAlign.right, style:TextStyle(color: Colors.white)),
                      isThreeLine: true,                       
                  ), 
                  );
                },
                itemCount: broadcast[widget.ind].contents.length,
              ))
        ],
      ),
    );
  }
}

class ExpandableContainer extends StatelessWidget {
  final bool expanded;
  final double expandedHeight;
  final Widget child;
  //final Color iconColor;

  ExpandableContainer({
    @required this.child,
    this.expandedHeight,
    this.expanded = true,
    //this.iconColor,
  });

  @override
  Widget build(BuildContext context) {
    double screenWidth = MediaQuery.of(context).size.width;
    return new AnimatedContainer(
      duration: new Duration(milliseconds: 100),
      curve: Curves.easeInOut,
      width: screenWidth,
      height: expanded ? expandedHeight : 0.0,
      child: new Container(
        child: child,
        decoration: new BoxDecoration(border: new Border.all(width: 1.0, color: Colors.blue)),
      ),
    );
  }
}

最佳答案

您需要将列表项设为状态 _iconColor

的 StatefulWidget

状态列表磁贴

class StatefulListTile extends StatefulWidget {
  const StatefulListTile({this.subtitle, this.title});
  final String subtitle, title;
  @override
  _StatefulListTileState createState() => _StatefulListTileState();
}

class _StatefulListTileState extends State<StatefulListTile> {
  Color _iconColor = Colors.white;
  @override
  Widget build(BuildContext context) {
    return new Container(
      decoration: new BoxDecoration(
          border: new Border.all(width: 1.0, color: Colors.grey),
          color: Colors.black),
      child: new ListTile(
        title: new Text(
          widget?.title ?? "",
          style: new TextStyle(
              fontWeight: FontWeight.bold, color: Colors.lightGreen),
          textAlign: TextAlign.right,
        ),
        leading: new IconButton(
          icon: Icon(Icons.star, color: _iconColor),
          onPressed: () {
            setState(() {
              _iconColor =
                  _iconColor == Colors.white ? Colors.yellow : Colors.white;
            });
          },
        ),
        subtitle: new Text(widget?.subtitle ?? "",
            textAlign: TextAlign.right, style: TextStyle(color: Colors.white)),
        isThreeLine: true,
      ),
    );
  }
}

用法


class ExpandableListView extends StatefulWidget {
  final String title;
  final int ind;

  const ExpandableListView({this.title, this.ind});

  @override
  _ExpandableListViewState createState() => new _ExpandableListViewState();
}

class _ExpandableListViewState extends State<ExpandableListView> {
  bool expandFlag = false;
  Color _iconColor = Colors.white;

  @override
  Widget build(BuildContext context) {
    return new Container(
      margin: new EdgeInsets.symmetric(vertical: 1.0),
      child: new Column(
        children: <Widget>[
          new Container(
            color: Colors.blue[300],
            padding: new EdgeInsets.symmetric(horizontal: 5.0),
            child: new Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                new IconButton(
                    icon: new Container(
                      height: 50.0,
                      width: 50.0,
                      decoration: new BoxDecoration(
                        color: Colors.deepOrange,
                        shape: BoxShape.circle,
                      ),
                      child: new Center(
                        child: new Icon(
                          expandFlag
                              ? Icons.keyboard_arrow_up
                              : Icons.keyboard_arrow_down,
                          color: Colors.white,
                          size: 30.0,
                        ),
                      ),
                    ),
                    onPressed: () {
                      setState(() {
                        expandFlag = !expandFlag;
                      });
                    }),
                new Text(
                  widget.title,
                  style: new TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 20.0,
                      color: Colors.black87),
                )
              ],
            ),
          ),
          new ExpandableContainer(
              expanded: expandFlag,
              expandedHeight: 90.0 *
                  (broadcast[widget.ind].contents.length < 4
                      ? broadcast[widget.ind].contents.length
                      : 4), // + (0.0 ?: 29.0),
              child: new ListView.builder(
                itemBuilder: (BuildContext context, int index) {
                  return StatefulListTile(
                    title: broadcast[widget.ind].contents[index],
                    subtitle:
                        '${broadcast[widget.ind].team[index]}\n${broadcast[widget.ind].time[index]}          ${broadcast[widget.ind].channel[index]}',
                  );
                },
                itemCount: broadcast[widget.ind].contents.length,
              ))
        ],
      ),
    );
  }
}

关于dart - Flutter: `onPressed` 作用于 ListView 中的所有 `IconButton`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55104585/

相关文章:

Flutter bloc 测试——emitsInorder 不发出初始状态

flutter - Flutter通过回调传递字符串

android - 仅在使用 flip_card 依赖项 [FLUTTER] 按下闪存卡应用程序的 nextButton 时显示正面

Dart pub 未下载依赖项

flutter - ParentDataWidget Positioned 想要将 StackParentData 类型的 ParentData 应用于 RenderObject

Flutter - 可拖动和缩放的小部件

flutter - 在 ListView 中显示复选框

Flutter 后退按钮隐藏在导航中

flutter - Dart/Flutter 主题类(class)代码的字符串转换

flutter - Flutter-如何在滚动到屏幕上时创建窗口小部件