Home > Net >  Calling a stateful widget from another stateful widget does not work as expected
Calling a stateful widget from another stateful widget does not work as expected

Time:02-21

Calling a statefulwidget from a button click of another widget does not do anything. What I am trying to do is execute a print statement just to see if the calling works

I have this ElevatedButton below which calls the Stateful Widget Contacts, I dont see any errors but I dont see the print statement printed out in the console.

    ElevatedButton(
      onPressed: () {
        const Contacts(name: 'Jimmy');
      },
      child: const Text('Fetch API data'),
    ),

class Contacts extends StatefulWidget {
  final String name;
  const Contacts({Key? key, required this.name}) : super(key: key);

  @override
  _ContactsState createState() => _ContactsState();
}

class _ContactsState extends State<Contacts> {
  @override
  Widget build(BuildContext context) {
    print('Test2');
    return Center(child: Text(widget.name));
  }
}

CodePudding user response:

State objects will not be created unless added to the widget tree.

CodePudding user response:

Maybe you could run the print statement in constructor? Try this way:

class Contacts extends StatefulWidget {
   final String name;
   const Contacts({Key? key, required this.name}) : super(key: key);

   @override
   _ContactsState createState() => _ContactsState();
}

class _ContactsState extends State<Contacts> {

 _ContactsState () {
    print('Test2');
 }
  @override
  Widget build(BuildContext context) {
    return Center(child: Text(widget.name));
  }
}
  • Related