Search code examples
firebaseflutterflutter-showmodalbottomsheet

How to pass data across Stateful widget?


So my question is i get data from firebase in first widget, then i click and open a bottomsheet through void -> another stateful widget, how can i pass the snapshot data from first widget to the other one?

Below code is not working...

....
Widget build(BuildContext context) {
          return Container(
              ElevatedButton(
                    child: Text('Request a tour'),
                    onPressed: () {
                      displayBottomSheet(context, widget.snapshot.data()["author"]);
                    },
                  ),
                );


    void displayBottomSheet(BuildContext context, String author) {  //updated
    showModalBottomSheet(
        context: context,
        builder: (ctx) {
          return BottomSheetWidget(author);  //updated
        });
  }

NEW ERROR: Too many positional arguments: 0 expected, but 1 found.

class BottomSheetWidget extends StatefulWidget {   

     final String author;                 //updated
     BottomSheetWidget({this.author});    //updated

     @override
  class _BottomSheetWidgetState createState() => _BottomSheetWidgetState();
}

class _BottomSheetWidgetState extends State<BottomSheetWidget> {

    Widget build(BuildContext context) {
          return Container(
                  new ElevatedButton(
                  child: Text('Send'),
                  onPressed: () {
                    requestTour(widget.author);     //updated
                  },
                ),
               .....
              }


    requestTour(String userName) async { 
    ...
    }

Solution

  • class BottomSheetWidget extends StatefulWidget {   
    
         final String author;                 //updated
         BottomSheetWidget(this.author);    //<-- remove {}
    
         @override
      class _BottomSheetWidgetState createState() => _BottomSheetWidgetState();
    }
    
    class _BottomSheetWidgetState extends State<BottomSheetWidget> {
    
        Widget build(BuildContext context) {
              return Container(
                      new ElevatedButton(
                      child: Text('Send'),
                      onPressed: () {
                        requestTour(widget.author);     //updated
                      },
                    ),
                   .....
                  }
    
    
        requestTour(String userName) async { 
        ...
        }