gpt4 book ai didi

Flutter 如何从 ListTile 更改所选图 block 的背景颜色

转载 作者:行者123 更新时间:2023-12-03 04:32:48 25 4
gpt4 key购买 nike

我正在尝试更改 ListTile 中选定图 block 的背景。

我搜索并找到了以下两个帖子,但没有一个能解决我的问题。

Post1 Post2

在@CopsOnRoad 的回答的帮助下,我变得更好了。

使用以下代码,如果我选择多个图 block ,所有图 block 都保持选中状态。如何一次只选一个,取消选上一个?

图 block 索引受itemCount: is books.length限制。

    List<Favorited> books;

// todo: this needs to be changed, has a hard coded value of 200
List<bool> _selected = List.generate(200, (i) => false); // Pre filled list

@override
Widget build(BuildContext context) {
final booksProvider = Provider.of<Model>(context);

return Container(
child: StreamBuilder(
stream: booksProvider.getUserFavList('103610812025'),
builder: (context, AsyncSnapshot<List<Favorited>> snapshot) {
if (snapshot.hasData) {
books= snapshot.data.toList();
return ListView.builder(
itemCount: books.length,
itemBuilder: (buildContext, index) {
return Container(
color: _selected[index] ? Colors.amber : Colors.transparent,
child: ListTile(
title: InkWell(
child: Text(snapshot.data[index].title),
onTap:() {
setState(() {
_selected[index] = !_selected[index];
});
}),
subtitle: Text(snapshot.data[index].name),
),
);
});
} else {
return Text('Fetching');
}
}),
);

最佳答案

让一个变量保存选定的图 block 索引。



List<Favorited> books;

// todo: this needs to be changed, has a hard coded value of 200
List<bool> _selected = List.generate(200, (i) => false); // Pre filled list
int selectedIndex;

@override
Widget build(BuildContext context) {
final booksProvider = Provider.of<Model>(context);

return Container(
child: StreamBuilder(
stream: booksProvider.getUserFavList('103610812025'),
builder: (context, AsyncSnapshot<List<Favorited>> snapshot) {
if (snapshot.hasData) {
books= snapshot.data.toList();
return ListView.builder(
itemCount: books.length,
itemBuilder: (buildContext, index) {
return Container(
color: selectedIndex == index ? Colors.amber : Colors.transparent,
child: ListTile(
title: InkWell(
child: Text(snapshot.data[index].title),
onTap:() {
setState(() {
selectedIndex = index;
});
}),
subtitle: Text(snapshot.data[index].name),
),
);
});
} else {
return Text('Fetching');
}
}),
);

关于Flutter 如何从 ListTile 更改所选图 block 的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64655361/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com