I have created a custom widget to display a tag/hashtag in my app.
help_form.dart
TagButton(
name: "Electricity",
onPressed: () {}),
TagButton(
name: "DIY",
onPressed: () {}),
TagButton(
name: "Programming",
onPressed: () {}),
However I want to know the text of the tag that was pressed so I can detect what tags the user has selected. At the moment, I’ve successfully been able to change the color of the tag that has been selected, but I’m not sure how to save it programatically in help_form.dart so I can then send it to the database.
Here is TagButton.dart:
class TagButton extends StatefulWidget {
final String name;
final void Function()? onPressed;
TagButton({super.key, required this.name, required this.onPressed});
@override
State<TagButton> createState() => _TagButtonState();
}
class _TagButtonState extends State<TagButton> {
bool chosenTag = false;
@override
Widget build(BuildContext context) {
return TextButton(
style: ButtonStyle(
backgroundColor: WidgetStatePropertyAll(
chosenTag == true ? CustomColors.secondaryColor : Colors.grey)),
onPressed: () {
print("Chosen tag is: ${chosenTag.toString()}");
print("Pressed ${widget.name}");
setState(() {
// widget.onPressed;
chosenTag == false ? chosenTag = true : chosenTag = false;
});
print("Chosen tag is: ${chosenTag.toString()}");
},
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.tag,
color: Colors.white,
),
Text(widget.name, style: TextStyle(color: Colors.white)),
],
));
}
}
Any idea?
2
Answers
You can get the selected tags by user in the parent of TagButton, you can find the sample code according to your provided code in here:
Also, you need to call the
onPress
parameter inside theTagButton
like the code below:Feel free to add comment if you expect more.
In your
TagButton
function, call theonPressed
function with the name as an arguement:Update the onPressed parameter type to pass the called value
You can now fetch the value from your custom widget like this:
See full code demo: https://dartpad.dev/?id=681651f61af15c05ac746d181752b725