0

How do I access the variable "selectedTag" from this statefulWidget:

class _AlertDialogOneState extends State<AlertDialogOne> {
  Item selectedTag;
...
  }
}

inside this statelessWidget :

class CardTile extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(...
Yusuf-Uluc
  • 887
  • 4
  • 15

2 Answers2

1

Pass it as parameter,

class CardTile extends StatelessWidget {
  final Item selectedTag;// Add this
  CardTile(this.selectedTag); // Add this

  @override
  Widget build(BuildContext context) {
    return Container(...
ikerfah
  • 2,612
  • 1
  • 11
  • 18
0

To pass this variable, you have multiple ways:

  • Pass it as a constructor when u navigate to this class using your navigator
Navigator.push(
context,
MaterialPageRoute(builder: (context) => CardTile(selectedTag)),
);
    class CardTile extends StatelessWidget {
    Item selectedTag;
    CardTile(this.selectedTag);
    @override
    Widget build(BuildContext context) {
        return Container(...
  • Use a state management like provider
    class ProviderData with ChangeNotifier {
    Item selected;

    void changeSelection(newSelect) {
    selected = newSelect;
    changeNotifier();
    }

    }

and inside any class you need call this:

final providerData = Provider.of<ProviderData>(context);

so you can access the variable or change it using this instance like this:

final variable = providerData.selected;
providerData.changeSelection(newValue);
print(variable);

hope this help but i see that it is better to pass it through the constructor if you are not using a state managemnt, however i just gave you an example for illustration

Ziyad Mansy
  • 427
  • 3
  • 9