Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();
        },
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading