在ListView.builder中更改特定的ListTile图标

时间:2020-03-23 21:33:57

标签: android flutter dart mobile

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

1 个答案:

答案 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(() {});
          },
        ),
      ),
    )

工作演示

enter image description here

完整代码

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