Reputation: 166
What I wanna do is that I have a ListView with icons and stuff, they are like little shortcuts for the most used functions in the app.
List _shortcuts = [
{
'name': 'HORN',
'icon': Icons.circle_outlined,
'selection': false,
'func': (String dummy) {
// do something
print('I did it!' + dummy);
},
},
].toList();
So my question is... is it possible to call each items unique function in the Listviews builder method?
Something like _shortcuts[i]['func']('wow')
?
Upvotes: 0
Views: 1200
Reputation:
You should create a class that will be used in your _shortcuts
list. See the example below:
// The ShortCut class.
class ShortCut {
final String name;
final IconData icon;
final bool selection;
final void Function(String) func;
const ShortCut({
required this.name,
required this.icon,
required this.selection,
required this.func,
});
}
This class can be used within a widget and the function can be accessed from within the builder method of the ListView
widget as follows:
class App extends StatefulWidget {
@override
_AppState createState() => _AppState();
}
class _AppState extends State<App> {
/// The is your list with custom shortcuts.
final _shortCuts = <ShortCut>[
ShortCut(
name: 'HORN',
icon: Icons.circle_outlined,
selection: false,
func: (String dummy) {
// do something
print('I did it!' + dummy);
},
),
];
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: _shortCuts.length,
itemBuilder: (context, index) {
final _shortCut = _shortCuts[index];
// Call the function here.
_shortCut.func('dummy');
return Container();
},
);
}
}
I hope that this is what you are looking for!
Upvotes: 1
Reputation: 3295
void main() {
List<Map<String, dynamic>> _short = [
{
'name': 'HORN',
'icon': "Icons.circle_outlined",
'selection': false,
'func': (String dummy) {
print('I did it! \t' + dummy);
},
}
];
_short[0]["func"]("hello");
}
Hopefully, this will be helpful to you.
Upvotes: 2