Sorry, I'm relatively new to Flutter and having some trouble. I want to initiate functions when I press my first, second, or third button. These buttons initiate map markers, polylines, etc. They work fine when assigned onPress with an icon button... I can't figure out how to get them to work with a ToggleButton... Do they have to be added to a list somehow? If so, how?
Here are my three buttons:
Consumer<ProviderMaps>(builder: (context, menu, widget) {
return Container(
padding: EdgeInsets.zero,
decoration: BoxDecoration(
border: Border.all(color: Colors.transparent, width: 1.0),
borderRadius: BorderRadius.all(Radius.circular(5.0)),
),
child: ToggleButtons(
selectedColor: Colors.red,
color: Colors.white,
children: <Widget>[
Icon(MdiIcons.vectorPolygon),
Icon(MdiIcons.ruler),
Icon(MdiIcons.pencil),
],
onPressed: (int index) {
setState(() {
for (int buttonIndex = 0;
buttonIndex < _selection.length;
buttonIndex++) {
if (buttonIndex == index) {
_selection[buttonIndex] = !_selection[buttonIndex];
} else {
_selection[buttonIndex] = false;
}
}
});
},
isSelected: _selection,
),
);
}),
My list:
List<bool> _selection = List.generate(3, (_) => false);
I'd like to call functions like these when I switch buttons:
menu.changestatutpolyg();
menu.changestatupolyli();
_initFreeDraw();
This is how I normally call these functions (works fine):
Consumer<ProviderMaps>(builder: (context, menu, widget) {
return IconButton(
icon: Icon(MdiIcons.ruler),
color: Color(0xffFFFFFF),
onPressed: () {
menu.changestatupolyli();
});
}),
Anybody know how to do this? Please advise.
Edit:
Attempt#:
onPressed: (int index) {
setState(
() {
switch (index) {
case 1:
{
menu.changestatutpolyg();
}
break;
case 2:
{
menu.changestatupolyli();
}
break;
case 3:
{
_initFreeDraw();
}
break;
}
},
);
},
isSelected: _selection,
),
);
}),
Well, the ToggleButtons
's onPressed
does provide you the index of the button pressed. So, the index would be 0 if the first button is pressed, one if the second, etc.
So in your onPressed, you can check the index, and based on that call the adequate function (regular if statements work fine as well):
onPressed: (int index) {
switch(index) {
case 0: {
callFunction1();
}
break;
case 1: {
callFunction2();
}
break;
//etc.
}
},
Or better, you can place the functions in an array (make sure to place them in the right order), and do something like:
var functions = <Function>[function1, function2, function3];
//...
//then, in the onPressed:
onPressed: (int index) {
//call the function of that index
functions[index]();
}
User contributions licensed under CC BY-SA 3.0