Peters Victor
Peters Victor

Reputation: 70

How to get the value of the selected Item in a list in flutter

I have a List of Widgets(A container with a different Texts Child), I have a map of Texts. The texts are different age ranges.

I have been able to change the color of the selected container.

How will i get the value of the text in the selected container.

Here is the List,

List.generate(
                    ageRange.length,
                      (index) {
                      return AgeSelector(
                        ageRange: ageRange[index],
                        textColor: selectedIndex == index ? Colors.white : Colors.black,
                        containerColor: selectedIndex == index ? kSecondaryColor :  Colors.white,
                        ageChoice: selectedIndex == index ? AgeRange(age: ageRange[index].toString()): Text('none'),
                        press: () {
                          setState(() {
                            selectedIndex = index;
                          });
                        },
                      );
                      }
                  ),

here's the AgeSelector Widget,

    class AgeSelector extends StatelessWidget {
  const AgeSelector({
    Key key,
    this.ageRange, this.textColor, this.containerColor, this.press, this.ageChoice,
  }) : super(key: key);


  final AgeRange ageRange;
  final Color textColor, containerColor;
  final GestureTapCallback press;
  final String ageChoice;

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: press,
      child: Container(
        height: getProportionateScreenWidth(80),
        width: getProportionateScreenWidth(70),
        decoration: BoxDecoration(
          color: containerColor,
          borderRadius: BorderRadius.circular(15)
        ),
        child: Center(
          child: Text(
            ageRange.age,
            style: TextStyle(
              fontSize: getProportionateScreenWidth(22),
              color: textColor,
              fontWeight: FontWeight.bold
            ),
          ),
        ),
      ),
    );
  }
}

And here's the ageRange Map

class AgeRange {
  final String age;

  AgeRange({
    @required this.age
  });
}

List <AgeRange> ageRange = [age1, age2, age3,age4];

AgeRange age1 = AgeRange(
  age : "10+"
);

AgeRange age2 = AgeRange(
    age : "20+"
);

AgeRange age3 = AgeRange(
    age : "30+"
);

AgeRange age4 = AgeRange(
    age : "40+"
);

Here's the Container

Upvotes: 1

Views: 1936

Answers (1)

Yakhyo Mashrapov
Yakhyo Mashrapov

Reputation: 390

If I understand you correctly, you need add this lines of code to your press callback:

selectedAge = ageRange[index].age;

Upvotes: 1

Related Questions