簡體   English   中英

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

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

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

class HiraganaPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          "Hiragana",
          style: TextStyle(
            color: Colors.white,
          ),
        ),
        centerTitle: true,
        backgroundColor: Colors.blueAccent,
      ),
      body: ListView.separated(
        separatorBuilder: (context, index) {
          return Divider(
            thickness: 3.0,
            height: 1.0,
          );
        },
        itemCount: data.length,
        itemBuilder: (context, index) {
          return Container(
            decoration: BoxDecoration(color: Colors.grey[300]),
            child: ListTile(
              leading: CircleAvatar(
                backgroundColor: Colors.white,
                radius: 28,
                child: Image.network(
                  data[index]["writing"],
                ),
              ),
              title: Text(
                "Text: " + data[index]["key"],
                style: TextStyle(
                  fontFamily: "Merienda",
                  fontSize: 18.22,
                ),
              ),
              subtitle: Text(
                "Reading: " + data[index]["reading"],
                style: TextStyle(
                  fontFamily: "Merienda",
                  fontSize: 18.22,
                ),
              ),
            ),
          );
         },
      ),
    );
  }
}

我在Flutter中做了一個ListView,但是現在這個ListView中有一些ListTiles可以選擇。 選擇后,我希望背景顏色更改為我選擇的顏色。 我不知道該怎么做。 在文檔中,他們提到 ListTile 具有屬性樣式。 但是,當我嘗試添加它時(如下面代碼中的倒數第三行),該樣式屬性在下方出現一條波浪狀的紅線,編譯器告訴我未定義命名參數“樣式”。

您可以用容器包裝 ListTile 並更改它的顏色。 這是該代碼的示例以及更改顏色的方法:

class Issue66349460 extends StatefulWidget {
  @override
  _Issue66349460State createState() => _Issue66349460State();
}

class _Issue66349460State extends State<Issue66349460> {
  List<Item> items = [
    Item(title: 'Item 1', color: Colors.red),
    Item(title: 'Item 2', color: Colors.blue),
    Item(title: 'Item 3', color: Colors.green),
  ];

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: items.length,
      itemBuilder: (context, index) {
        return Container(
          color: items[index].color,
          child: ListTile(
            title: Text(items[index].title),
            onTap: () => changeListTileColor(items[index]),
          ),
        );
      }
    );
  }

  void changeListTileColor(Item item){
    setState(() {
      item.color = Colors.deepPurple;
    });
  }
}

class Item {
  String title;
  Color color;

  Item({@required this.title, this.color});
}

暫無
暫無

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

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