Search code examples
flutterroutesmodelnavigation

i want to send my model class object to next screen previously i do it like this first i declare object in the second screen


Hello i want to send my model class object to next screen previously i do it like this first i declare object in the second screen where i want to naviagte

 class ContactsDetail extends StatelessWidget {
      ContactModel contactDetail;
      ContactsDetail({Key? key, required this.contactDetail}) : super(key: key);
    
    Then in navigator i passed the argument  
    
        onTap: () async {
                
                    Navigator.of(context).push(MaterialPageRoute<void>(builder: (BuildContext context) {
                        return ContactsDetail(
                          contactDetail: contactlist[index],);
                      },
                    ));
                  },`enter code here`

Which works perfectly, Now i am working with name routes and i want to send the whole model of current index data same as i do above but i am unable to do this Now here is my routes .

Route<dynamic> generateRoute(RouteSettings settings){
switch(settings.name)
{
  case LoginScreen.routeName:
  return MaterialPageRoute(builder: (context) => const LoginScreen());
  case TourDetailScreen.routeName:
    return MaterialPageRoute(builder: (context) => TourDetailScreen());

  default:
    return errorRoute();
}
}

And here is the class to which i want to send data

class TourDetailScreen extends StatelessWidget {
  static const routeName = 'tourist_detail_screen';
  TourModel tourDetails;
  TourDetailScreen({Key? key,required this.tourDetails}) : super(key: key);

and this is main 
MaterialApp(
        debugShowCheckedModeBanner: false,

        initialRoute: TouristHomeScreen.routeName,
        onGenerateRoute: (settings) => generateRoute(settings),
      ),

Solution

  • There are several ways to do this but here is how I send object of my custom model to next screen

    First of all in your genrateRoute declare a variable as your model you want to send

    Route<dynamic> generateRoute(RouteSettings settings){
    var tourModel = settings.arguments as TourModel;
    

    Inside your case pass the above variable as argument

    case TourDetailScreen.routeName:
      return MaterialPageRoute(builder: (context) => TourDetailScreen(arguments : tourModel));
    

    From where you want to navigate,Navigate like this

    Navigator.of(context).push(MaterialPageRoute(builder: (BuildContext context){
              return TourDetailScreen(
                arguments: toursList[index],
              );
            })
    

    And finally in the screen where you want to navigate

    TourModel arguments;
    TourDetailScreen({Key? key,required this.arguments}) : super(key: key);
    

    and use can use arguments where ever you want inside build i.e Text(arguments.yourFields),