DefaultKiller
DefaultKiller

Reputation: 27

Dynamically add an item to a List widget

I'm using GUI framework called Fyne for Go. How can I dynamically add an item to an array that List widget uses? The code:

var componentsList = []string{"test1: test1"}

func main() {
    app := app.New()
    window := app.NewWindow("Delta Interface")

    componentsTree := widget.NewList(
        func() int {
            return len(componentsList)
        },
        func() fyne.CanvasObject {
            return widget.NewLabel("template")
        },
        func(i widget.ListItemID, o fyne.CanvasObject) {
            o.(*widget.Label).SetText(componentsList[i]) // i need to update this when componentsList was updated
        })

    nameEntry := widget.NewEntry()
    typeEntry := widget.NewEntry()

    form := &widget.Form{
        Items: []*widget.FormItem{
            {Text: "Name", Widget: nameEntry},
            {Text: "Type", Widget: typeEntry}},
        OnSubmit: func() {
            componentsList = append(componentsList, nameEntry.Text+": "+typeEntry.Text) // append an item to componentsList array
        },
    }

    layout := container.New(layout.NewGridWrapLayout(fyne.NewSize(350, 500)), componentsTree, form)
    window.SetContent(layout)

    window.Resize(fyne.NewSize(800, 600))
    window.ShowAndRun()
}

I wrote what I need to do in the comments in the code above:

  1. I need to update this when componentsList was updated.
  2. Append an item to componentsList array

Upvotes: 2

Views: 1518

Answers (1)

andy.xyz
andy.xyz

Reputation: 3265

After updating the data that the List renders you need just to call Refresh(). So simply update your OnSubmit function to:

        OnSubmit: func() {
            componentsList = append(componentsList, nameEntry.Text+": "+typeEntry.Text)
            componentsTree.Refresh()
        },

Upvotes: 1

Related Questions