Home > OS >  Fyne List widget doesn't display items correctly
Fyne List widget doesn't display items correctly

Time:11-10

I'm trying to display the alphabet in a listwithdata widget. I am using a custom clickable label as the widget to display in the list.
For some reason everything displays fine when the widget loads. But when I start scrolling the letters starts being displayed in a completely random order and I cant figure out why.
Here is a fully working code to reproduce the bug.

package main

import (
    "fmt"

    "fyne.io/fyne/v2"
    "fyne.io/fyne/v2/app"
    "fyne.io/fyne/v2/data/binding"
    "fyne.io/fyne/v2/widget"
)

func makeAlphabet() []string {
    var alphabet []string
    for ch := 'A'; ch <= 'Z'; ch   {
        alphabet = append(alphabet, string(ch))
    }
    return alphabet
}

type TapLabel struct {
    *widget.Label //composition

    //function pointers to set to get events
    OnTapped func(string)
}

func (mc *TapLabel) Tapped(pe *fyne.PointEvent) {
    if mc.OnTapped != nil {
        mc.OnTapped(mc.Text)
    }
}

func NewTapLabel(text string, tappedLeft func(string)) *TapLabel {
    return &TapLabel{widget.NewLabel(text), tappedLeft}
}

func alphabetToBrands(letter string) {
    fmt.Println(letter)
}

func main() {
    app := app.New()
    window := app.NewWindow("tac_hub")
    window.Resize(fyne.NewSize(200,200))

    rawData := makeAlphabet()
    data := binding.BindStringList(&rawData)
    list := widget.NewListWithData(
        data,
        func() fyne.CanvasObject {
            return NewTapLabel("template", alphabetToBrands)
        },
        func(i binding.DataItem, o fyne.CanvasObject) {
            o.(*TapLabel).Bind(i.(binding.String))
        },
    )

    window.SetContent(list)
    window.ShowAndRun()
}

The click action works correctly and gives me the correct letter (not the one that is displayed but the one that should be displayed).
I'm guessing I must be doing something wrong somewhere but I can't figure out what.

If anyone can help it would be appreciated!

CodePudding user response:

This works:

    list := widget.NewListWithData(
        data,
        func() fyne.CanvasObject {
            return &widget.Label{Text: "template"}
        },
        func(i binding.DataItem, o fyne.CanvasObject) {
            o.(*widget.Label).Bind(i.(binding.String))
        },
    )
    list.OnSelected = func(id widget.ListItemID) {
        fmt.Println(rawData[id])
    }

Dropping your custom TapLabel in favor of &widget.Label{Text: "template"}, then to print the tapped item you use list.OnSelected and close around the data slice.

CodePudding user response:

Looks like the argument here o.(*TapLabel).Bind(i.(binding.String)) changes as the scroll action happens. Add a log to observe the i.(binding.String) value in that function as you scroll

Take a look at this: list example

  • Related