Flutter: A variable passed to the next screen becomes null

Viewed 735

I want to pass a variable to the next screen but it becomes null in the next screen. what am I wrong with this? My code is like below.

first_screen.dart

onTap: () {
            print(doc);  // Prints out Instance of `DocumentSnapshot` on log
            Navigator.of(context).pushNamed('/second', arguments: doc);
          },

second_screen.dart

class SecondScreen extends StatefulWidget {
  final DocumentSnapshot doc;

  SecondScreen({
    this.doc,
  });

  @override
  State<StatefulWidget> createState() {
    return _SecondScreenStateState();
  }
}

class _SecondScreenState extends State<SecondScreen> {
    @override
    void initState() {
        super.initState();
        print(widget.doc);  // Prints out null here
    }

I tried with othe data types but all variables become null in the next screen.

2 Answers

You have to pass argument like this:

Navigator.of(context).pushNamed('/second', arguments: doc);

for you is true but, use the ModalRoute.of() method to returns the current route with the arguments like this:

  final doc = ModalRoute.of(context).settings.arguments as String;

I assumed that doc is String.

If you're sharing data between widgets (screens) try looking at InheritedWidget.Take a look at https://www.youtube.com/watch?v=1t-8rBCGBYw. You can also look at state management packages like provider which is pretty easy to understand or a bloc. These will save you in the long run.

Related