Values in map changing after refresh

132 views Asked by At

Im trying to create a map that remembers its values when the page is recalled. I declared it outside the function so it would remain the same but the map still initializes to the defauly=t values when the page is recalled. How can i get it to remeber its values?

var rememberExpand =  make(map[int]bool{})

func (c *CollapsibleWithOption) Layout(gtx layout.Context, header, body func(C) D, more func(C), wallet_ID int) layout.Dimensions {
    fmt.Println(rememberExpand)
    for c.button.Clicked() {
        c.isExpanded = !c.isExpanded
    }

    rememberExpand[wallet_ID] = c.isExpanded
    fmt.Println(rememberExpand)

    icon := c.collapsedIcon
    if c.isExpanded {
        icon = c.expandedIcon
    }


                        
                    )
                })
            }),
            layout.Rigid(func(gtx C) D {
                if rememberExpand[wallet_ID] {
                    return body(gtx)
                }
                return D{}
            }),
        )
    })
}
1

There are 1 answers

5
Thijs van der Heijden On

Try defining the map as `var rememberExpand map[int]bool.

This however, leads to a new problem. The first time you reference this map, it will be nil, because it won't have been made yet. We can fix this fairly easily by checking if the map is equal to nil, and if it is, create a new map:

var rememberExpand map[int]bool

func (c *CollapsibleWithOption) Layout(gtx layout.Context, header, body func(C) D, more func(C), wallet_ID int) layout.Dimensions {
    if rememberExpand == nil { // Check if the map has been initialized yet
      rememberExpand = make(map[int]bool) // If not, create a new map
    }

    for c.button.Clicked() {
        c.isExpanded = !c.isExpanded
    }

    rememberExpand[wallet_ID] = c.isExpanded
    fmt.Println(rememberExpand)

    icon := c.collapsedIcon
    if c.isExpanded {
        icon = c.expandedIcon
    }


                        
                    )
                })
            }),
            layout.Rigid(func(gtx C) D {
                if rememberExpand[wallet_ID] {
                    return body(gtx)
                }
                return D{}
            }),
        )
    })
}