在Flutter中选择后更改ListTile的背景颜色

Rob*_*ert 13 user-interface listview background-color dart flutter

我做了一个ListView在颤振,但现在我有一些ListTiles在此ListView可以选择.选择后,我希望背景颜色更改为我选择的颜色.我不知道该怎么做.在文档中,他们提到a ListTile有一个属性style.但是,当我尝试添加它时(如下面代码中的第三行),此style属性在下面获得一条波浪形的红线,编译器告诉我The named parameter 'style' isn't defined.

Widget _buildRow(String string){
  return new ListTile(
    title: new Text(string),
    onTap: () => setState(() => toggleSelection(string)),
    selected: selectedFriends.contains(string),
    style: new ListTileTheme(selectedColor: Colors.white,),
  );
}
Run Code Online (Sandbox Code Playgroud)

Cop*_*oad 25

截屏:

在此处输入图片说明


简短的回答:

ListTile(
  tileColor: isSelected ? Colors.blue : null, 
)
Run Code Online (Sandbox Code Playgroud)

完整代码:

// You can also use `Map` but for the sake of simplicity I'm using two separate `List`.
final List<int> _list = List.generate(20, (i) => i);
final List<bool> _selected = List.generate(20, (i) => false); // Fill it with false initially
  
Widget build(BuildContext context) {
  return Scaffold(
    body: ListView.builder(
      itemBuilder: (_, i) {
        return ListTile(
          tileColor: _selected[i] ? Colors.blue : null, // If current item is selected show blue color
          title: Text('Item ${_list[i]}'),
          onTap: () => setState(() => _selected[i] = !_selected[i]), // Reverse bool value
        );
      },
    ),
  );
}
Run Code Online (Sandbox Code Playgroud)

  • @Richardd 创建一个变量 `int selectedIndex = -1`,然后检查 `if (index == selectedIndex)` 方法。如果您不明白,请单独提出问题,我会回答。 (3认同)

Bag*_*ata 14

我能够改变使用的ListTile的背景颜色BoxDecoration集装箱

ListView (
    children: <Widget>[
        new Container (
            decoration: new BoxDecoration (
                color: Colors.red
            ),
            child: new ListTile (
                leading: const Icon(Icons.euro_symbol),
                title: Text('250,00')
            )
        )
    ]
)
Run Code Online (Sandbox Code Playgroud)

  • Container()的color属性也将足够。 (2认同)

her*_*ert 11

如果您还需要onTap具有波纹效果的监听器,则可以使用Ink

ListView(
  children: [
    Ink(
      color: Colors.lightGreen,
      child: ListTile(
        title: Text('With lightGreen background'),
        onTap() { },
      ),
    ),
  ],
);
Run Code Online (Sandbox Code Playgroud)

连锁反应

  • @Augusto ListTile已经包含一个“ InkWell”,这是产生波纹效果的唯一条件。因此,如果在具有`onTap`处理函数的`ListTile`中没有涟漪效应。您正在做一些非常奇怪的事情。(仅当您想要背景颜色时,才需要使用我班的Ink小部件,因为当将“容器”和“ color”一起使用时,波纹效果会绘制在该颜色以下,因此不可见)。如果您不更改背景颜色,并且在ListTile或InkWell中使用onTap,则应该具有波纹效果。 (2认同)
  • 请记住,至少有一个祖先需要是 Material 小部件,否则这将不起作用 (2认同)

Rus*_*mov 10

包裹ListTile在一个Ink.

Ink(
  color: isSelected ? Colors.blue : Colors.transparent,
  child: ListTile(title: Text('hello')),
)
Run Code Online (Sandbox Code Playgroud)


rit*_*itz 8

一种简单的方法是将初始索引存储在变量中,然后在每次点击时更改该变量的状态。

   ListView.builder(
              shrinkWrap: true,
              itemCount: 4,
              itemBuilder: (context, index) {
                return Container( //I have used container for this example. [not mandatory]
                    color: tappedIndex == index ? Colors.blue : Colors.grey,
                    child: ListTile(
                        title: Center(
                      child: Text('${index + 1}'),
                    ),onTap:(){
                          setState((){
                            tappedIndex=index;
                          });
                        }));
              })
Run Code Online (Sandbox Code Playgroud)

完整代码:

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: MyWidget(),
    );
  }
}

class MyWidget extends StatefulWidget {
  @override
  MyWidgetState createState() => MyWidgetState();
}

class MyWidgetState extends State<MyWidget> {
  late int tappedIndex;

  @override
  void initState() {
    super.initState();
    tappedIndex = 0;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
          ListView.builder(
              shrinkWrap: true,
              itemCount: 4,
              itemBuilder: (context, index) {
                return Container(
                    color: tappedIndex == index ? Colors.blue : Colors.grey,
                    child: ListTile(
                        title: Center(
                      child: Text('${index + 1}'),
                    ),onTap:(){
                          setState((){
                            tappedIndex=index;
                          });
                        }));
              })
        ]));
  }
}

Run Code Online (Sandbox Code Playgroud)

Dartpad链接:https://dartpad.dev/250ff453b97cc79225e8a9c657dffc8a


Rém*_*let 7

并非ListTile具有该style属性。但是ListTileThemeListTileTheme是一个InheritedWidget。和其他人一样,它是用来传递下来(这里如主题)的数据。

要使用它,您必须在ListTile 上方包装任何ListTileTheme包含所需值的小部件。

ListTile然后将根据最接近的ListTileTheme实例本身设置主题。

  • 这是标记的正确答案,但是,我仍然不确定如何更改背景颜色。 (9认同)
  • 不幸的是,`ListTileTheme`没有backgroundColor属性,只有一个selectedColor属性。```this.dense = false,this.style = ListTileStyle.list,this.selectedColor,this.iconColor,this.textColor,this.contentPadding,```编辑:RIP格式 (3认同)

Mil*_*mar 6

不幸的是,ListTile 没有背景颜色属性。因此,我们必须简单地将 ListTile 小部件包装到 Container/Card 小部件中,然后我们就可以使用它的颜色属性。此外,我们必须提供具有一定高度的 SizedBox 小部件来分隔相同颜色的 ListTiles。

我正在分享对我有用的方法:)

我希望它一定会对你有所帮助。

屏幕截图:看看它是如何工作的

            return 
              ListView(
                children: snapshot.data.documents.map((doc) {
                  return Column(children: [
                    Card(
                      color: Colors.grey[200],
                       child: ListTile(
                      leading: Icon(Icons.person),
                      title: Text(doc.data['coursename'], style: TextStyle(fontSize: 22),),
                      subtitle: Text('Price: ${doc.data['price']}'),
                      trailing: IconButton(
                        icon: Icon(Icons.delete),
                        onPressed: () async {
                          await Firestore.instance
                              .collection('courselist')
                              .document(doc.documentID)
                              .delete();
                        },
                      ),
                  ),
                    ),
                 SizedBox(height: 2,)
                  ],);
                }).toList(),[enter image description here][1]
              );
Run Code Online (Sandbox Code Playgroud)


Bha*_*sai 6

这不再是痛苦!

现在你可以使用tileColorselectedTileColor财产ListTile控件去实现它。

看看这个问题 #61347,它被合并到 master 中。

  • 如果您正在运行“master”分支,这应该是可接受的答案。截至 2020 年 7 月 29 日,Flutter 的“stable”和“beta”分支不支持此功能。 (3认同)

Ale*_*dar 5

我知道原来的问题已经得到解答,但我想添加如何设置按下图块时的颜色ListTile。您正在寻找的属性被调用,并且可以通过将 包装在小部件中highlight color来设置它,如下所示:ListTileTheme

Theme(
  data: ThemeData(
    highlightColor: Colors.red,
  ),
  child: ListTile(...),
  )
);

Run Code Online (Sandbox Code Playgroud)

注意:如果Theme小部件重置 内文本元素的字体ListTile,只需将其fontFamily属性设置为您在应用程序中其他位置使用的相同值。