Flutter call function of another widget

I try to call a function named _callMe from AlertDialog .

this is my example code :

import 'package:flutter/material.dart';

void main() {
  runApp(const MainApplication());
}

class MainApplication extends StatelessWidget {
  const MainApplication({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      debugShowCheckedModeBanner: false,
      title: "Training",
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  Future<void> _callMe() async {
    print('Call Me ... !');
  }

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      child: const Text("Open Modal"),
      onPressed: () => {
        showDialog(
          context: context,
          builder: (_) {
            return SampleModal(callFunction: _callMe);
          },
        ),
      },
    );
  }
}

class SampleModal extends StatelessWidget {
  final Function callFunction ;
  const SampleModal({Key? key, required this.callFunction}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      content: ElevatedButton(
        onPressed: () {
          callFunction;
        },
        child: const Text("Call Me"),
      ),
    );
  }
}

Please explain to me what part of my code has problem ?

UPDATE:
I also changed function to this but still does not work:

void _callMe() {
    print('Call Me ... !');
  }

>Solution :

Replace this:

        onPressed: () {
          callFunction;
        },

with this:

        onPressed: () {
          callFunction();
        },

Leave a Reply