Search code examples
flutterclassdartparametersmaterialpageroute

How to pass many parameters from one page to another in flutter


...
onTap: () {
 Navigator.push(
     context,
     MaterialPageRoute(
      builder: (context) => CategoryPage(
              snapshot.data[index]),
     ));
},
...

Using the above code i try to pass the service id and the service type to the category page ... class CategoryPage extends StatefulWidget { // final String serviceId; // final String service_type; final String categorydata;

  CategoryPage(data, {key, this.categorydata}) : super(key: key);

  // @override
  // CategoryPage(categorydata) {
  //   this.serviceId = categorydata.serviceId;
  //   this.service_type = categorydata.serviceId;
  // }

  _CategoryPageState createState() =>
      _CategoryPageState(categorydata.toString());
 }

 class _CategoryPageState extends State<CategoryPage> {
  String id = "";
  _CategoryPageState(String categorydata) {
    this.id = categorydata.serviceId;
  }
...

From the above code, I need to get the service id and service type and display the tile of the Category page with the service type parameter. Please help me on achieving this result


Solution

  • You have to pass the data like this using the categorydata parameter from CategoryPage constructor.

    onTap: () {
     Navigator.push(
         context,
         MaterialPageRoute(
          builder: (context) => CategoryPage(
                 categorydata: snapshot.data[index]),
         ));
    },
    

    Here you need to define a final variable inside your StatefulWidget class and initialize it from the constructor;

    CategoryPage({key,required this.categorydata}) : super(key: key);
    
    final Album categorydata;
    
    _CategoryPageState createState() =>
        _CategoryPageState();
    }
    

    Then you can access it from the State class methods using widget keyword class, you don't need to pass it.

     class _CategoryPageState extends State<CategoryPage> {
    
    
       @override
      void initState() {
        super.initState();
        // access them from here
    
       final categorydata = widget.categorydata;
       final String serviceId = categorydata.service_id;
       final String service_type = categorydata. service_type;
    
      }
    
      @override
      Widget build(BuildContext context) {
        // access them from here
        final categorydata = widget.categorydata;
        final String serviceId = categorydata.service_id;
        final String service_type = categorydata. service_type;
       }
    
      }