Search code examples
gouser-interfacefyne

Binding Table data in Go Fyne


Fyne beginner here.

There is simple use case I'm trying to solve, without finding any solution in the docs: in Fyne, how to have a Table widget, with its data bound to a data source?

In other words, we have the binding.BindStringList in the docs, that allows to bind a list of strings…

data := binding.BindStringList(
    &[]string{"Item 1", "Item 2", "Item 3"},
)

…I am looking for something similar that would allow to bind a list of structs instead of string. For example, a table of todos:

type Todo struct {
  UserID    int    `json:"userId,omitempty"`
  ID        int    `json:"id,omitempty"`
  Title     string `json:"title,omitempty"`
  Completed bool   `json:"completed,omitempty"`
}

If it is not possible, what would seem like the best workaround for you?


Well, following Andy's suggestion, I tried this:

var data []Todo

stringData := `[{"userId":1,"id":1,"title":"delectus aut autem"},{"userId":1,"id":2,"title":"quis ut nam facilis et officia qui"}]`
json.Unmarshal([]byte(stringData), &data)

var bindings []binding.DataMap

for _, todo := range data {
  bindings = append(bindings, binding.BindStruct(&todo))
}

list := widget.NewTable(
  func() (int, int) {
    return len(bindings), 4
  },
  func() fyne.CanvasObject {
    return widget.NewLabel("wide content")
  },
  func(i widget.TableCellID, o fyne.CanvasObject) {
    title, _ := bindings[i.Row].GetItem("Title")
    log.Println(title)
    o.(*widget.Label).SetText(title)
  }
)

I don't manage to access the actual values of my elements (i.e. Title). Could you help?


Solution

  • Unfortunately there is not currently a data bound Table widget. In v2.1 we plan to add binding.BindMapList which would be passed to NewTableWithData. In the upcoming release.

    Until then you can maintain a slice of binding.DataMap items and access the items in it to bind the individual items inside the Table update callback methods.