簡體   English   中英

在 Flutter 中選擇時更改 ListTile 的背景顏色

[英]Change background color of ListTile upon selection in Flutter

我在 Flutter 中做了一個ListView ,但是現在這個ListView中有一些ListTiles可以選擇。 選擇后,我希望背景顏色更改為我選擇的顏色。 我不知道該怎么做。 文檔中,他們提到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,),
  );
}

截屏:

在此處輸入圖像描述


簡短的回答:

ListTile(
  tileColor: isSelected ? Colors.blue : null, 
)

完整代碼:

// 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
        );
      },
    ),
  );
}

我能夠使用Container內的BoxDecoration更改 ListTile 的背景顏色:

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

如果你還需要一個帶有漣漪效果的onTap監聽器,你可以使用Ink

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

連鎖反應

具有style屬性的不是ListTile 但是ListTileTheme ListTileTheme是一個繼承的Widget。 和其他人一樣,它用於傳遞數據(例如這里的主題)。

要使用它,您必須使用包含所需值的ListTileTheme將 ListTile上方的任何小部件包裝起來。

然后ListTile將根據最近的ListTileTheme實例對自身進行主題化。

ListTile包裹在Ink中。

Ink(
  color: isSelected ? Colors.blue : Colors.transparent,
  child: ListTile(title: Text('hello')),
)

這不再是痛苦了!

現在您可以使用ListTile小部件的tileColorselectedTileColor屬性來實現它。

看看這個已合並到 master 的問題 #61347

一種簡單的方法是將初始索引存儲在變量中,然后在點擊時更改該變量的狀態。

   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;
                          });
                        }));
              })

完整代碼:

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;
                          });
                        }));
              })
        ]));
  }
}

飛鏢板鏈接: https ://dartpad.dev/250ff453b97cc79225e8a9c657dffc8a

我知道原始問題已得到解答,但我想添加如何在按下瓷磚時設置ListTile的顏色 您要查找的屬性稱為highlight color ,可以通過將ListTile包裝在Theme小部件中來設置它,如下所示:

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

注意:如果Theme小部件重置ListTile中文本元素的字體,只需將其fontFamily屬性設置為您在應用程序的其他位置使用的相同值。

不幸的是, ListTile 沒有 background-color 屬性。 因此,我們必須簡單地將 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]
              );

我用過

ListTile(
                title: Text('Receipts'),
                leading: Icon(Icons.point_of_sale),
                tileColor: Colors.blue,
              ),  

有兩個道具:tileColor 和 selectedTileColor。

tileColor - 當瓷磚/行未被選中時;

selectedTileColor - 當瓷磚/行被選中時

ListTile(
        selected: _isSelected,
        tileColor: Colors.blue,
        selectedTileColor: Colors.greenAccent,
)

我可以通過將 ListTile 設為 Container Widget 的子級並向 Container Widget 添加顏色來更改其背景顏色。

這里的drawerItem 是保存isSelected 值的模型類。 背景顏色取決於 isSelected 值。

注意:對於未選中的項目,請保持顏色透明,這樣您仍然可以獲得漣漪效果。

 for (var i = 0; i < drawerItems.length; i++) {
      var drawerItem = drawerItems[i];
      drawerOptions.add(new Container(
        color: drawerItem.isSelected
            ? Colors.orangeAccent
            : Colors.transparent,
        child: new ListTile(
          title: new Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[Text(drawerItem.title), drawerItem.count],
          ),
          leading: SvgPicture.asset(
            drawerItem.icon,
            width: 34,
            height: 34,
          ),
          onTap: () {
            _handleNavigation(i);
          },
          selected: drawerItem.isSelected,
        ),
      ));
    }

在此處輸入圖像描述

您的答案已在Github中得到解答。

Card(
  color: Colors.white,
  shape: ContinuousRectangleBorder(
    borderRadius: BorderRadius.zero,
  ),
  borderOnForeground: true,
  elevation: 0,
  margin: EdgeInsets.fromLTRB(0,0,0,0),
  child: ListTile(
    // ...
  ),
)

在此處輸入圖像描述>使變量

        int slectedIndex;

隨叫隨到

     onTap:(){
                      setState(() {
                      selectedIndex=index;
                     })

瓷磚屬性

            color:selectedIndex==index?Colors.red :Colors.white,

與列表視圖生成器相同

        ListView.builder(
                          itemCount: 10,
                          scrollDirection:Axis.vertical,
                          itemBuilder: (context,index)=>GestureDetector(
                            onTap:(){
                              setState(() {
                                selectedIndex=index;
                              });
                              
                            } ,
                            child: Container(
                              margin: EdgeInsets.all(8),
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(5),
                                color:selectedIndex==index?Colors.red :Colors.white,
                              ),)

將 Material 小部件與 InkWell 小部件一起使用,然后將 ListTile 放入其中,如下例所示:

return Material(
      color: Colors.white,
      child: ListTile(
          hoverColor: Colors.greenAccent,
          onLongPress: longPressCallback,
          title: Text(
            '$taskTitle',
            style: TextStyle(
                decoration: isChecked
                    ? TextDecoration.lineThrough
                    : TextDecoration.none),
          ),
          trailing: Checkbox(
              activeColor: Colors.lightBlueAccent,
              value: isChecked,
              onChanged: checkboxCallback)),
    );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM