Home > Net >  Read nested widget/class properties value in flutter
Read nested widget/class properties value in flutter

Time:11-24

I'm building a simple app with lots of nested widgets/classes from different specialised files

list of files:

main.dart -> the menu file used to start the activity "Activity()"

group_widgets.dart -> the file that contains the custom widget "CustomWidget()"

file_a.dart -> the file that uses the custom widgets inside the "Activity()"

other.dart -> other files that needs to manage data changed in CustomWidget()

inside main.dart:

onPressed: () {
 Navigator.push(
  context,
  MaterialPageRoute(
   builder: (context) => const Activity(),
 ));
},

inside group_widgets.dart:

class CustomWidget extends StatefulWidget {
  const CustomWidget({Key? key}) : super(key: key);

  @override
  State<CustomWidget> createState() => _CustomWidgetState();
}

class _CustomWidgetState extends State<CustomWidget> {
  var _boolean = false;
  bool switchBoolean(bool state) => !state;

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: () => {
        setState(() {
          _boolean = switchBoolean(_boolean);
        })
      },
      child: Container(
        color: _boolean == true ? Colors.green : Colors.red,
      ),
    );
  }
}

inside file_a.dart

class Activity extends StatefulWidget {
  const Activity({Key? key}) : super(key: key);

  @override
  State<Activity> createState() => _ActivityState();
}

class _ActivityState extends State<Activity> {
  @override
  Widget build(BuildContext context) {

    bool boolean = true;

    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: const [
            CustomWidget(),
            Text('Here where to show the variable from CustomWidget'
                'and prove I can retrieve it')
          ],
        ),
      ),
    );
  }
}

inside other.dart

if ( booleanFromCustomWidget == true) {
  Something ...
}

What is the best practice to achieve it? I've read a lot here but nothing seems to well fit my needing.

Just comment if my request is not as clear as it seems to me))

CodePudding user response:

Please correct me if I am wrong, but if you want to access data from parent widgets from inside their descendants (children or even nested children) you can either pass them down via parameter arguments:

 Child(int age, String name);

And then accept it in the new file, where the Child widget lives, via its constructor:

class Child{
  String name;
  int age;
     
  // Constructor
  Child(String passedName, int passedAge) {
    this.name = passedName;
    this.age = passedAge;
   
  }
}

Inside the parent.dart you then have to import the children.dart to use it.

Or use a popular package like the provider package: https://pub.dev/packages/provider This allows you to store data containers, which you can access basically anywhere in your code. Feel free to google it & watch some tutorials to get started, as it is the preffered approach to avoid passing data to widget which really do not care about the passed parameters.

Note: You can transfer the idea to output the String data like in your example code above.

CodePudding user response:

you can use a state manager like provider, or bloc At the top level, you set up the data services

  • Related