Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: A variable passed to the next screen becomes null

Tags:

flutter

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.

like image 864
Ooto Avatar asked Mar 11 '26 11:03

Ooto


1 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.

like image 137
Cyrus the Great Avatar answered Mar 13 '26 09:03

Cyrus the Great