Issue with spawning buttons and assigning listeners

So, I’m creating a bunch of buttons and trying to give them all the same method on click but it should be different based on the key each button possesses. However, they all call the exact same key (which is the last one added). I am very confused at what’s going on or why they all use the same same string. Anyone know what’s going on with adding listeners in a for loop? Here’s the code I call in start

public void populateVisibleNames()
{

for(int i = 0; i<visibleNames.Count; i++)
{
    Transform newButton = Instantiate(namePrefabButton) as Transform;
    newButton.SetParent(buttonPanel.transform);
    Button b = newButton.GetComponent<Button>();
    b.onClick.AddListener(() => disablePanel(nameButton, visibleNames[i-1].ToString()));
    newButton.GetChild (0).GetComponent<Text>().text = visibleNames*.ToString();*

nameButtons.Add(b);
newButton.gameObject.SetActive(true);
newButton.transform.localPosition = new Vector3(0,-i*30,0);
}
}

I was facing some similar issues recently. This is how I solved it. Save the name to a local variable and the use that variable.

     for(int i = 0; i<visibleNames.Count; i++)
     {
         Transform newButton = Instantiate(namePrefabButton) as Transform;
         newButton.SetParent(buttonPanel.transform);
         Button b = newButton.GetComponent<Button>();

         string btn_name = visibleNames[i-1].ToString();         

         b.onClick.AddListener(() => disablePanel(nameButton, btn_name));
         newButton.GetChild (0).GetComponent<Text>().text = visibleNames*.ToString();*

nameButtons.Add(b);
newButton.gameObject.SetActive(true);
newButton.transform.localPosition = new Vector3(0,-i*30,0);
}
Here’s the snippet if my code if it helps you by any chance :
if(!languagesSet){

  •  foreach(LanguagePack lp in languageList){*
    
  •  	GameObject langbtn = Instantiate(Resources.Load<GameObject>("LangButton"));*
    
  •  	langbtn.transform.SetParent(GameObject.Find("VerticalPanel").transform);*
    
  •  	langbtn.name = lp.Id;*
    
  •  	langbtn.GetComponent<RectTransform>().localScale = Vector3.one;*
    
  •  	langbtn.GetComponentInChildren<UnityEngine.UI.Text>().text = lp.Id;*
    
  •  	string str = lp.Id;*
    
  •  	langbtn.GetComponent<UnityEngine.UI.Button>().onClick.AddListener(() => { changeLanguage(str);});*
    
  •  languagesSet=true;*
    
  •  }*
    
  •  }*