容器图标在选择一项时全部更改

时间:2019-02-06 16:19:06

标签: dart flutter

我是新手,这是我的问题, 选择图标后,我将选择容器中的所有其他项目

选择后,我无法将容器的颜色更改为绿色 不仅在图标上,而且在按下容器功能时

class _AddEmpToProjectState extends State<AddEmpToProject> {
  bool _isSelected = false;
  Container addEmpListTile() {
    return Container(
        margin: EdgeInsets.fromLTRB(10.0, 0.0, 10.0, 10.0),
        padding: EdgeInsets.all(5.0),
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10.0), color: Colors.white),
        child: Container(
          child: ListTile(
              leading: CircleAvatar(
                backgroundImage: AssetImage('assets/tom.jpg'),
              ),
              title: Text('Sam'),
              subtitle: Text('Site Manager'),
              trailing: InkWell(
                  onTap: () {
                    _isSelected = !_isSelected;
                    setState(() {});
                  },
                  child: _isSelected
                      ? Icon(
                          Icons.done,
                          color: Colors.green,
                          size: 35.0,
                        )
                      : Icon(
                          Icons.add,
                          color: Colors.deepPurple,
                          size: 35.0,
                        ))),
        ));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.deepPurple,
      appBar: AppBar(
        title: Text('Add Employees'),
        elevation: 0.0,
        actions: <Widget>[
          IconButton(
            icon: Icon(
              Icons.search,
              color: Colors.white,
            ),
            onPressed: () {},
          ),
          IconButton(
            icon: Icon(
              Icons.done,
              color: Colors.white,
            ),
            onPressed: () {},
          )
        ],
      ),

      body: ListView.builder(
        itemCount: 10,
        itemBuilder: (BuildContext context, int index) {
          return addEmpListTile();
        },
      ),

    );
  }
}

在轻按容器时,将颜色更改为绿色,并应移至顶部 如果取消选择必须返回到数组小部件索引 这是我应该做的

1 个答案:

答案 0 :(得分:0)

不仅需要选择一个项目(布尔值),还需要以某种方式跟踪选择了哪个项目(某种标识符)。

一种解决方案是使用index作为跟踪号码

class _AddEmpToProjectState extends State<AddEmpToProject> {
  -bool _isSelected = false;
  +Set<int> _selected = Set();

...
class _AddEmpToProjectState extends State<AddEmpToProject> {
 Set<int> _selected = Set();

 Container addEmpListTile(int index) {

    ...
    onTap: () {
     setState(() {
       if(_selected.contains(index)) {
        _selected.remove(index);
       } else {
         _selected.remove(index);
       };
     }
    },
    child: _selected.contains(index)
       ? Icon(Icons.done)
       : Icon(Icons.add)
  }

...

  build() {
    ...
    itemBuilder: (BuildContext context, int index) {
        return addEmpListTile(index);  // <-- add index here
    ...
  }