我对Flutter和Dart还是比较陌生,所以我对ListView操作有疑问。当前,下面的代码可以工作并在ListView中显示一些基本信息。 我将如何实现一个解决方案,以便当我单击特定的列表图块时,其图标变为其他内容?以下是我当前的股票代码:
import 'package:flutter/material.dart';
void main() => runApp(MaterialApp(
home: HomePage(),
));
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
Widget _getListItemTile(BuildContext context, int index) {
return Card(
child: GestureDetector(
child: ListTile(
leading: Icon(Icons.check_box_outline_blank),
title: Text('My Item'),
onTap: () {},
),
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('My Test App'),
centerTitle: true,
),
body: ListView.builder(
itemCount: 7,
itemBuilder: _getListItemTile,
),
);
}
}
答案 0 :(得分:2)
您可以在下面复制粘贴运行完整代码
您可以声明List<bool>
并通过leading
更改boolList[index]
图标
代码段
List<bool> boolList = [true, true, true, true, true, true, true];
...
Card(
child: GestureDetector(
child: ListTile(
leading: boolList[index]
? Icon(Icons.check_box_outline_blank)
: Icon(Icons.place),
title: Text('My Item'),
onTap: () {
boolList[index] = !boolList[index];
setState(() {});
},
),
),
)
工作演示
完整代码
import 'package:flutter/material.dart';
void main() => runApp(MaterialApp(
home: HomePage(),
));
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
List<bool> boolList = [true, true, true, true, true, true, true];
Widget _getListItemTile(BuildContext context, int index) {
return Card(
child: GestureDetector(
child: ListTile(
leading: boolList[index]
? Icon(Icons.check_box_outline_blank)
: Icon(Icons.place),
title: Text('My Item'),
onTap: () {
boolList[index] = !boolList[index];
setState(() {});
},
),
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('My Test App'),
centerTitle: true,
),
body: ListView.builder(
itemCount: boolList.length,
itemBuilder: _getListItemTile,
),
);
}
}