Navigator pass class arguments with pushNamed - Flutter

Viewed 24

I'm trying to pass some arguments using Navigator pushNamed and one of those arguments is a class as shown below (I just wrote the beginning of the classes).

class TestTO {
int? idTest;
String? title;
String? subTitle;
List<TopicTest>? listTopic;
    ...to be continue
}  

class TopicTest {
int id;
String name;
String nameFile;
    ...to be continue
}

So, I capture the data of these classes on my main screen and I want to pass some of them to other screens, and I did the following:

TestTO? testClass; //instance class

Navigator.of(context).pushNamed('/pdfPage', arguments: {
  'id': idContrato.toString(),
  'title': title,
  'listTopic':'${(testClass.listTopic)}',
});

On my pdfPage screen where I want to use the sent data I did the following:

TestTO? testClass; //instance class
int? id;
String? title;

initState() {
   super.initState();
   Future.delayed(Duration.zero, () {
      setState(() {
        final routeArgs1 = ModalRoute.of(context)!.settings.arguments! as Map;
        id = int.parse(routeArgs1["id"]!);
        title= routeArgs1["title"]!;
        testClass!.listTopic= routeArgs1["listTopic"]! as List<TopicTest>?;
       });
     });
   }

id and title are working correctly, however testClass I am getting error when compiling, when I go to debug this writing "listTopic" -> "[Instance of 'TestTO']"

The error I get sending the route:

@pragma("vm:external-name", "Error_throwWithStackTrace") external static Never _throw(Object error, StackTrace stackTrace);

Could anyone give me tips? I'm new to programming so maybe I'm wrong.

1 Answers

You don't need to convert the argument to and from a map - that is best reserved for simple objects like int/float/String. If you want to pass a more complex object, like an object of the TestTO class, then just pass it as the argument and retrieve it like this: final arg = ModalRoute.of(context)!.settings.arguments as TestTO;. If you want to pass multiple complex objects then just wrap those in a simple class that holds those objects, and pass that wrapper.

See the documentation for a great example.

Related