flutter on listitem tap code example

Example 1: how to change style of selected index in listview.builder in flutter

//Example to change Color of selected index in Listview in Flutter.


class ChangeListViewBGColor extends StatefulWidget {
  _ChangeListViewBGColorState createState() => _ChangeListViewBGColorState();
}

class _ChangeListViewBGColorState extends State<ChangeListViewBGColor> {
  final List<String> _listViewData = [
    "A List View with many Text - Here's one!",
    "A List View with many Text - Here's another!",
    "A List View with many Text - Here's more!",
    "A List View with many Text - Here's more!",
    "A List View with many Text - Here's more!",
    "A List View with many Text - Here's more!",
  ];

  int _selectedIndex = 0;

  _onSelected(int index) {
    setState(() => _selectedIndex = index);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Change ListView Bg Color Example'),
      ),
      body: ListView.builder(
        itemCount: _listViewData.length,
        itemBuilder: (context, index) => Container(
              color: _selectedIndex != null && _selectedIndex == index
                  ? Colors.red
                  : Colors.white,
              child: ListTile(
                title: Text(_listViewData[index]),
                onTap: () => _onSelected(index),
              ),
            ),
      ),
    );
  }
}

Example 2: highlight/un-highlight the selected interest upon pressed in flutter

import 'package:flutter/material.dart';import 'package:swipe_listview_selection/list_item_model.dart';class MyHomePage extends StatefulWidget {@override_MyHomePageState createState() => _MyHomePageState();}class _MyHomePageState extends State<MyHomePage> {List<ListItem<String>> list;@overridevoid initState() {super.initState();populateData();}void populateData() {list = [];for (int i = 0; i < 10; i++)     list.add(ListItem<String>("item $i"));}@overrideWidget build(BuildContext context) {return Scaffold(appBar: AppBar(title: Text("List Selection"),),body: ListView.builder(itemCount: list.length,itemBuilder: _getListItemTile,),);}Widget _getListItemTile(BuildContext context, int index) {return GestureDetector(onTap: () {if (list.any((item) => item.isSelected)) {setState(() {list[index].isSelected = !list[index].isSelected;});}},onLongPress: () {setState(() {list[index].isSelected = true;});},child: Container(margin: EdgeInsets.symmetric(vertical: 4),color: list[index].isSelected ? Colors.red[100] : Colors.white,child: ListTile(title: Text(list[index].data),),),);}}

Tags:

Misc Example