1

I'm having an issue with passing dynamic arguments to a button callback with Fyne. I'm trying to create a list of buttons that when clicked will call a function with a specific string argument:

  clients := []fyne.CanvasObject{}
  for _, uuidStr := range uuidStrs {
    clientBtn := widget.NewButton(uuidStr, func() { server.selectClient(uuidStr))
    clients = append(clients, clientBtn)
  } 
  clientsListed := container.New(layout.NewGridLayout(1), clients...)

The issue is that all of the buttons, when clicked, will select the last client e.g. it will call server.selectClient(uuidStr) where uuidStr is always uuidStrs[len(uuidStrs)-1], but I want each button to pass in a unique uuidStr. All of the buttons display the correct string, but don't pass the correct string in the callback.

How can I get the buttons, when clicked, to select the client it displays?

4

1 回答 1

0

This is due to how Go re-uses variables in loop iterations. You need to "capture" the value so that the button callback func gets the right value. As follows:

  clients := []fyne.CanvasObject{}
  for _, uuidStr := range uuidStrs {
    uuid := uuidStr
    clientBtn := widget.NewButton(uuidStr, func() { server.selectClient(uuid))
    clients = append(clients, clientBtn)
  } 
  clientsListed := container.New(layout.NewGridLayout(1), clients...)
于 2021-06-23T11:01:51.370 回答