Yusuf-Uluc
Yusuf-Uluc

Reputation: 1065

How do I access an variable from a StatefulWidget inside an StatelessWidget?

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(...

Upvotes: 0

Views: 172

Answers (2)

Ziyad Mansy
Ziyad Mansy

Reputation: 437

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

Upvotes: 0

ikerfah
ikerfah

Reputation: 2862

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(...

Upvotes: 1

Related Questions