1

I have a stateful widget that has one method called in initialisation. I wanna know how to be able to get a parameter from the previous screen and pass it in initState to my initialisation method

class LabDetalheWidget extends StatefulWidget {
  final String path;

  const LabDetalheWidget({
    Key key,
    this.path,
  }) : super(key: key);

2 Answers2

1

You can pass parameter like that

class MyWidget extends StatefulWidget {
  final String param;

  const MyWidget({
    Key key,
    this.param,
  }) : super(key: key);
  
  @override
  _MyWidgetState createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  @override
    void initState() {
      print(widget.param);
      super.initState();
    }
  @override
  Widget build(BuildContext context) {
    return Container(
      
    );
  }
}

Inside the state you can access the parameter like that

print(widget.param)

YoBo
  • 2,292
  • 3
  • 9
  • 25
  • What is that Key –  Feb 20 '21 at 16:22
  • It's a good practice to pass it to the super of StatefullWidget. You can check documentation on what is a key. https://api.flutter.dev/flutter/foundation/Key-class.html – YoBo Feb 20 '21 at 16:23
  • well, I have this code to get that page: `Navigator.of(context).pushNamed(AppRoutes.LAB_DETALHE, arguments: item.elemento != null ? item.elemento.fullPath : subPath);` –  Feb 20 '21 at 16:25
  • Where do I pass the parameter –  Feb 20 '21 at 16:25
  • I'm guessing you are using MaterialApp' onGenerateRoute method. So there you can pass the parameter. The you showed is correrct but you need to pass it one more time when you are creating the instance of your widget inside onGenerateRoute. – YoBo Feb 20 '21 at 16:33
  • ` case AppRoutes.LAB_DETALHE: return MaterialPageRoute( builder: (_) => LabDetalheWidget(path: settings.arguments,));` –  Feb 20 '21 at 16:40
  • I wrote this in generateRoute and still doesn't work –  Feb 20 '21 at 16:41
  • Do you get any error or what? The param is null inside the statefullwidget? Can we see the widget code? – YoBo Feb 20 '21 at 16:42
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/228997/discussion-between-armstrong-and-yobo). –  Feb 20 '21 at 16:42
0

I believe you wanna pass data across routes.. If so then read this flutter cookbook's section you might get the idea https://flutter.dev/docs/cookbook/navigation/passing-data

KR Tirtho
  • 447
  • 5
  • 13