Implementing DataItem and DataList #4020
-
Hello, I have read the book of fyne toolkit and I want to improve my app by using data binding. I have no idea where to start. Thanks in advance. Love fyne btw, It's by far the best documented toolkit ! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 5 replies
-
Using complex types like this you may be better off not using data binding all the way, it can get a little difficult on list and tree with custom types. However if you want to explore this further you probably need |
Beta Was this translation helpful? Give feedback.
-
Attempting to emulate data coming from reading an SQL database. There is an additional step to convert the slice of typed structs returned from the SQL read into to a func main() {
myApp := app.New()
myWindow := myApp.NewWindow("List Data")
myWindow.Resize(fyne.Size{800, 600})
type user struct {
ID int
Name string
Active bool
}
item1 := user{
ID: 1,
Name: "User 1",
Active: true,
}
item2 := user{
ID: 2,
Name: "User 2",
Active: false,
}
item3 := user{
ID: 3,
Name: "User 3",
Active: true,
}
l := []any{item1, item2, item3}
data := binding.NewUntypedList()
data.Set(l)
list := widget.NewListWithData(data,
func() fyne.CanvasObject {
return widget.NewLabel("template")
},
func(i binding.DataItem, o fyne.CanvasObject) {
t, _ := i.(binding.Untyped).Get()
bt := binding.NewString()
user := t.(user)
bt.Set(user.Name)
o.(*widget.Label).Bind(bt)
})
add := widget.NewButton("Append", func() {
val := user{
ID: data.Length()+1,
Name: fmt.Sprintf("Item %d", data.Length()+1),
Active: true,
}
data.Append(val)
})
myWindow.SetContent(container.NewBorder(nil, add, nil, nil, list))
myWindow.ShowAndRun()
} |
Beta Was this translation helpful? Give feedback.
Using complex types like this you may be better off not using data binding all the way, it can get a little difficult on list and tree with custom types.
However if you want to explore this further you probably need
binding.BindUntypedList(...)
that should at least get you started - though it may require a fair amount of casts initially before you find a prettier way to wrap it in a custom type for your specific struct.