skip to Main Content

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


  1. 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:

    class HomePage extends StatefulWidget {
      const HomePage({super.key});
    
      @override
      State<HomePage> createState() => _HomePageState();
    }
    
    class _HomePageState extends State<HomePage> {
      var selectedTags = <String>[];
    
      void updateSelectedTags(String tag) {
        if (selectedTags.contains(tag)) {
          setState(() {
            selectedTags.remove(tag);
          });
        } else {
          setState(() {
            selectedTags.add(tag);
          });
        }
      }
    
      @override
      Widget build(BuildContext context) {
        print("Selected tags: $selectedTags");
        return Scaffold(
          body: Column(
            children: [
              TagButton(name: "Electricity", onPressed: () => updateSelectedTags("Electricity")),
              TagButton(name: "DIY", onPressed: () => updateSelectedTags("DIY")),
              TagButton(name: "Programming", onPressed: () => updateSelectedTags("Programming")),
            ],
          ),
        );
      }
    }
    

    Also, you need to call the onPress parameter inside the TagButton like the code below:

    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 ? Colors.amber : Colors.grey)),
            onPressed: () {
              print("Chosen tag is: ${chosenTag.toString()}");
              print("Pressed ${widget.name}");
              setState(() {
                chosenTag == false ? chosenTag = true : chosenTag = false;
              });
              print("Chosen tag is: ${chosenTag.toString()}");
              // add onPress parameter here to invoke the function
              if (widget.onPressed != null) {
                widget.onPressed!();
              }
            },
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Icon(
                  Icons.tag,
                  color: Colors.white,
                ),
                Text(widget.name, style: TextStyle(color: Colors.white)),
              ],
            ));
      }
    }
    

    Feel free to add comment if you expect more.

    Login or Signup to reply.
  2. In your TagButton function, call the onPressed function with the name as an arguement:

    return TextButton(
             onPressed: () {
               widget.onPressed?.call(widget.name);},
    

    Update the onPressed parameter type to pass the called value

    final void Function(String)? onPressed;
    

    You can now fetch the value from your custom widget like this:

    TagButton(
      name: "Electricity", 
      onPressed: (selectedValue) {
        print('User clicked on $selectedValue');}),
    TagButton(
      name: "DIY", 
      onPressed: (selectedValue) {
        print('User clicked on $selectedValue');}),
    TagButton(
      name: "Programming", 
      onPressed: (selectedValue) {
        print('User clicked on $selectedValue');}),
    

    See full code demo: https://dartpad.dev/?id=681651f61af15c05ac746d181752b725

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search