Open In App

Flutter – Pass a Function as an Argument From One Screen to Another

Last Updated : 16 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In Flutter, you can pass a function as an argument from one screen (widget) to another screen (widget) by defining a callback function and passing it as an argument when navigating or pushing to the new screen. Here’s a step-by-step guide on how to do this:

Required Tools

To build this app, you need the following items installed on your machine:

  • Visual Studio Code / Android Studio
  • Android Emulator / iOS Simulator / Physical Device device.
  • Flutter Installed
  • Flutter plugin for VS Code / Android Studio.

A sample video is given below to get an idea about what we are going to do in this article.

Step By Step Implementations

Step 1: Create a New Project in Android Studio

To set up Flutter Development on Android Studio please refer to Android Studio Setup for Flutter Development, and then create a new project in Android Studio please refer to Creating a Simple Application in Flutter.

Step 2: Import the Package

First of all import material.dart file.

import 'package:flutter/material.dart';

Step 3: Execute the main Method

Here the execution of our app starts.

Dart




void main() {
  runApp(MyApp());
}


Step 4: Create MyApp Class

In this class we are going to implement the MaterialApp , here we are also set the Theme of our App.

Dart




class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.green, // Set the app's primary theme color
      ),
      home: FirstScreen(),
    );
  }
}


Step 5: Create FirstScreen Class

In this class, we are going to implement a scaffold to display our UI, and Here we are also declaring the callback function and navigate the second screen by passing the callback funtion to its constructor.

Dart




class FirstScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('First Screen')),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            // Navigate to the SecondScreen when the button is pressed
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => SecondScreen(callback: sayHello),
              ),
            );
          },
          child: Text('Go to Second Screen'),
        ),
      ),
    );
  }
  
  // Callback function to be passed to the SecondScreen
  String sayHello() {
    return "Hello From the First Screen";
  }
}


Step 6: Create SecondScreen Class

In this class we are going to call the callback method from the FirstScreen and display a hello message in the SecondScreen.

Dart




class SecondScreen extends StatefulWidget {
  final Function callback;
  
  SecondScreen({required this.callback});
  
  @override
  _SecondScreenState createState() => _SecondScreenState();
}
  
class _SecondScreenState extends State<SecondScreen> {
  String message = "";
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Second Screen')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('Welcome to the Second Screen'),
            ElevatedButton(
              onPressed: () {
                // Execute the callback function and update the message
                setState(() {
                  message = widget.callback();
                });
              },
              child: Text('Say Hello'),
            ),
            Text(
              message,
              style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20),
            ), // Display the message here
          ],
        ),
      ),
    );
  }
}


Here is the complete code of the above article:

Dart




import 'package:flutter/material.dart';
  
void main() {
  runApp(MyApp());
}
  
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.green, // Set the app's primary theme color
      ),
      home: FirstScreen(),
    );
  }
}
  
class FirstScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('First Screen')),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            // Navigate to the SecondScreen when the button is pressed
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => SecondScreen(callback: sayHello),
              ),
            );
          },
          child: Text('Go to Second Screen'),
        ),
      ),
    );
  }
  
  // Callback function to be passed to the SecondScreen
  String sayHello() {
    return "Hello From the First Screen";
  }
}
  
class SecondScreen extends StatefulWidget {
  final Function callback;
  
  SecondScreen({required this.callback});
  
  @override
  _SecondScreenState createState() => _SecondScreenState();
}
  
class _SecondScreenState extends State<SecondScreen> {
  String message = "";
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Second Screen')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('Welcome to the Second Screen'),
            ElevatedButton(
              onPressed: () {
                // Execute the callback function and update the message
                setState(() {
                  message = widget.callback();
                });
              },
              child: Text('Say Hello'),
            ),
            Text(
              message,
              style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20),
            ), // Display the message here
          ],
        ),
      ),
    );
  }
}


Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads