Search code examples
flutterparametersparameter-passing

passing a parameter to the navigated window in flutter


I have reviewed several documents and S.O entries but could not find an really easy sample to be able to test in my app. I just want to -simply- pass a string (or int...etc.) value to the next screen that I open by pressing a button.

Here is core block of my second page receivingpage.dart (which will receive the data):

 import 'package:flutter/material.dart';

 class receivingpage extends StatefulWidget {
  const receivingpage({super.key});

  @override
  _receivingpageState createState() => _receivingpageState(receiveddata:'mystring');
  }  

class _receivingpageState extends State<receivingpage> {

final String receiveddata;
_examinationState({required this.receiveddata}); 

@override
Widget build(BuildContext context) {
 return Scaffold(.... the rest of the code...

and here is the first page (senderpage.dart) which sends the data to the next page :

 onTap: ()
  => Navigator.push(context,
 MaterialPageRoute(builder: (context) =>   examination( <******> ),), 
    ),

when I put the parameter name (receiveddata which I defined in the first page) the place here: <******> , it doesn't accept and returns the following error:

The named parameter 'receiveddata' isn't defined. Try correcting the name to an existing named parameter's name, or defining a named parameter with the name 'gelenParametre'.


Solution

  • You're doing it Wrong. You're trying to pass the data in state class.

    class ReceivingPage  extends StatefulWidget {
    
      final String data;
    
      const ReceivingPage ({super.key,required this.data});
    
      @override
      State<ReceivingPage > createState() => _ReceivingPage State();
    }
    
    class _ReceivingPage State extends State<ReceivingPage > {
      @override
      Widget build(BuildContext context) {
        return const Placeholder();
      }
    }