Fyne: Wrong button's tapped event called

Created on 25 Jun 2019  路  2Comments  路  Source: fyne-io/fyne

I have a VBox widget that holds a dynamic amount of buttons which are loaded in from a database:

services, err := data.LoadServices(user)
if err != nil {
    log.Println("Error while retrieving services,", err)
    return widget.NewVBox()
}
serviceButtons := widget.NewVBox()
for _, service := range services {
    serviceButtons.Append(
        widget.NewButton(service.Name, func() {
            log.Printf("button pressed, service: %s", service.Name)
        }),
    )
}

The buttons are displayed as expected, however when I click any of them, the tapped function of the last button is executed.

Most helpful comment

Unfortunately this is a subtlety of how Go assigns variables in a for loop. You need to include in the loop

capturedService := service

And then use capturedService In your print statement. This is because the access to the service variable is delayed until the callback executes and so it sees the last value for service.

All 2 comments

Unfortunately this is a subtlety of how Go assigns variables in a for loop. You need to include in the loop

capturedService := service

And then use capturedService In your print statement. This is because the access to the service variable is delayed until the callback executes and so it sees the last value for service.

Was struggling with this since I'm new to Go thanks for the information ^^

Was this page helpful?
0 / 5 - 0 ratings

Related issues

develar picture develar  路  6Comments

boussou picture boussou  路  9Comments

mhf-ir picture mhf-ir  路  6Comments

semyon-dev picture semyon-dev  路  4Comments

Jacalz picture Jacalz  路  4Comments