颤振:尝试使用 OnTap 突出显示列表磁贴



我正在尝试弄清楚如何突出显示选定的ListTile,因此我只编辑数据库中突出显示的Tile的值。

一些上下文代码,以备不时之需。

User_List.飞镖

class UserList extends StatefulWidget {
@override
_UserListState createState() => _UserListState();
}
class _UserListState extends State<UserList> {
@override
Widget build(BuildContext context) {
final users = Provider.of<List<Camper>>(context) ?? [];
return ListView.builder(
itemCount: users.length,
itemBuilder: (context, index){
return UserTile(user: users[index]);
},
);
}
}

以下是我试图让 OnTap 工作的代码。

User_Tile.飞镖

class UserTile extends StatelessWidget {
final Camper user;
UserTile({this.user});
@override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.only(top: 8.0),
child: Card(
elevation: 10.0,
color: Colors.blue[100],
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
margin: EdgeInsets.fromLTRB(20.0, 6.0, 20.0, 0.0),
child: ListTile(
leading: Text('ID: ${user.camperID}'),
title: Text(user.name),
subtitle: Text(user.instrument),
//Dense compacts the text together more
dense: true,
trailing: Text(user.band + ' Band'),
),
),
);
}
}

我使用onTap或onPress的大多数尝试都失败了,我对Flutter没有足够的经验,所以我想我会在这里问一下,看看是否有人知道。

如果您需要我的更多信息,请告诉我。谢谢。

使用statefulwidget而不是statelesswidget

class UserList extends StatefulWidget {
@override
_UserListState createState() => _UserListState();
}
class _UserListState extends State<UserList> {
@override
Widget build(BuildContext context) {
int selectedIndex = 0;
final users = Provider.of<List<Camper>>(context) ?? [];
return ListView.builder(
itemCount: users.length,
itemBuilder: (context, index){
return Padding(
padding: EdgeInsets.only(top: 8.0),
child: Card(
elevation: 10.0,
color: Colors.blue[100],
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
margin: EdgeInsets.fromLTRB(20.0, 6.0, 20.0, 0.0),
child: Container(
child: ListView.builder(
padding: EdgeInsets.only(left: 10.0),
itemCount: users.length,
itemBuilder: (BuildContext context, int index) {
return GestureDetector(
onTap: () {
setState(() {
selectedIndex = index;
});
},
child: ListTile(
leading: Text('ID: ${users.camperID}'),
title: Text(users.name,style: TextStyle(
color: index == selectedIndex
? Colors.white
: Colors.white60,
fontWeight: FontWeight.bold,
fontSize: 24.0,
letterSpacing: 1.2),),
subtitle: Text(users.instrument),
//Dense compacts the text together more
dense: true,
trailing: Text(users.band + ' Band'),
),
);
}
),
),
),
);
},
);
}
}

您是否尝试过将其包装在手势检测器中?

最快的方法是将ListTile包装在ListView内并使用ListTile属性onTap(),因为没有它就不会产生实质性的涟漪效应,并且还需要通过添加shrinkwrap: true来收缩包装Listview元素,因此只需要所需的空间n不会占用所有空间,您可以为每个ListTile项提供一个墨水属性,该属性可以采用不同的随心所欲地着色。我知道现在回答为时已晚,但这是最简单的方法,可能会帮助其他人,

尝试下面的代码,

ListView( shrinkWrap: true,
children: <Widget>[
ListTile(
onTap: () {},
leading: Icon(
Icons.home,
color: Colors.black,
),
title: Text('Home'),
),],
),

最新更新