Change background color of ListTile upon selection in Flutter

前端 未结 12 1765
闹比i
闹比i 2020-12-15 03:10

I\'ve made a ListView in Flutter, but now I have some ListTiles in this ListView that can be selected. Upon selection, I want the back

12条回答
  •  再見小時候
    2020-12-15 04:03

    Screenshot:


    Solution:

    // you can do that by using `Map` but for simplicity I used 2 separate `List`. 
    List _list = List.generate(20, (i) => i);
    List _selected = List.generate(20, (i) => false); // initially fill it up with false
    
    Widget build(BuildContext context) {
      return Scaffold(
        appBar: AppBar(),
        body: ListView.builder(
          itemBuilder: (_, i) {
            return Container(
              margin: const EdgeInsets.symmetric(vertical: 2),
              color: _selected[i] ? Colors.blue : null, // if current item is selected show blue color
              child: ListTile(
                title: Text("Item ${_list[i]}"),
                onTap: () => setState(() => _selected[i] = !_selected[i]), // reverse bool value
              ),
            );
          },
        ),
      );
    }
    

提交回复
热议问题