I want to mark the ListTile
of the current page as selected but 2 days ago I\'m looking for a general way to do it.
I saw examples like this one where you h
Simple create enum class like below.
enum DrawerSelection { home, favorites, settings}
Create enum object and pass pre-defined value if you want, in my case i pass home as selected ListTile item. Like below code.
class _MyHomePage extends State<MyHomePage> {
DrawerSelection _drawerSelection = DrawerSelection.home;
Then in ListTile use selected property and change enum onTap() like below code.
ListTile(
selected: _drawerSelection == DrawerSelection.home,
title: Text('Home'),
leading: Icon(Icons.home),
onTap: () {
Navigator.pop(context);
setState(() {
_drawerSelection = DrawerSelection.home;
_currentWidget = MainWidget();
_appBarTitle = Text("Home");
});
},
),
ListTile(
selected: _drawerSelection == DrawerSelection.favorites,
title: Text('Favorites'),
leading: Icon(Icons.favorite),
onTap: () {
Navigator.pop(context);
setState(() {
_drawerSelection = DrawerSelection.favorites;
_currentWidget = FavoritesWidget();
_appBarTitle = Text("Favorites");
});
},
),
ListTile(
selected: _drawerSelection == DrawerSelection.settings,
title: Text('Settings'),
leading: Icon(Icons.settings),
onTap: () {
Navigator.pop(context);
setState(() {
_drawerSelection = DrawerSelection.settings;
_currentWidget = SettingsWidget();
_appBarTitle = Text("Settings");
});
},
),
i think it is just simple you can create a new class that have your data and the bool selected
class Post {
final bool selected;
var data;
Post({
this.selected,
this.data
});
}
now when you use LIstView.builder in the itemBuilder if list[index].selected is true then set the color to blue if not then let it white or whatever in the on tap or onpressed whatever you are you using save the last clicked index in a global variable(called savedIndex)-initialize it with (-1)- and change selected to true at the this list index,then if savedIndex wasnt equal -1 change list[savedIndex].selected=false.
global variable
int selectedIndex =-1;
and itemBuilder.
itemBuilder: (BuildContext _context, int i) {
return GestureDetector(
child:
Container(
decoration: new BoxDecoration(
borderRadius: new BorderRadius.circular(16.0),
color:_list[index].selected? Colors.blue:colors.white,
),
child: _buildRow(_list[index]),) ,
onTap: () {
setState(){
if(savedIndex!=-1){
list[savedIndex].selected=false
}
_list[index].selected=true;
savedIndex=index;
}
}
);
}