How to call child method from parent for another widget

main.dart

import 'dart:io';
import 'package:audioplayer/audioplayer.dart';
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:path_provider/path_provider.dart';
import 'package:record_mp3/record_mp3.dart';
import 'package:permission_handler/permission_handler.dart';
import 'regitration.dart';
//import 'voiceCreate.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String statusText = "";
  bool isComplete = false;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Builder(
        builder: (context) => Scaffold(
          drawer: Drawer(
            elevation: 2.0,
            child: ListView(
              children: <Widget>[
                ListTile(
                  title: Text('Home'),
                  onTap: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) {
                          return MyApp();
                        },
                      ),
                    );
                  },
                ),
                ListTile(
                  title: Text('Sign up'),
                  onTap: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) {
                          return LoginScreen();
                        },
                      ),
                    );
                  },
                ),
                ListTile(
                  title: Text('Sign in'),
                  onTap: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) {
                          return LoginScreen();
                        },
                      ),
                    );
                    // add sign in page
                  },
                ),
              ],
            ),
          ),
          floatingActionButton: FloatingActionButton(
            onPressed: () {
              // Add your onPressed code here!
            },
            child: Icon(Icons.add),
            backgroundColor: Colors.tealAccent.shade700,
          ),
          backgroundColor: Colors.grey.shade900,
          appBar: AppBar(
            title: Text('Myvo'),
            centerTitle: true,
            backgroundColor: Colors.tealAccent.shade700,
          ),
          body: Column(children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Expanded(
                  child: GestureDetector(
                    child: IconButton(
                        icon: Icon(Icons.mic),
                        color: Colors.white,
                        iconSize: 40,
                        onPressed: () async {
                          startRecord();
                        }),
                  ),
                ),
                Expanded(
                  child: GestureDetector(
                    child: IconButton(
                        icon: Icon(Icons.pause),
                        color: Colors.white,
                        iconSize: 40,
                        onPressed: () async {
                          pauseRecord();
                        }),
                  ),
                ),
                Expanded(
                  child: GestureDetector(
                    child: IconButton(
                        icon: Icon(Icons.stop),
                        color: Colors.white,
                        iconSize: 40,
                        onPressed: () async {
                          stopRecord();
                        }),
                  ),
                ),
              ],
            ),
            Padding(
              padding: const EdgeInsets.only(top: 20.0),
              child: Text(
                statusText,
                style: TextStyle(color: Colors.red, fontSize: 20),
              ),
            ),
            GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: () {
                play();
              },
              child: Container(
                margin: EdgeInsets.only(top: 30),
                alignment: AlignmentDirectional.center,
                width: 100,
                height: 50,
                child: isComplete && recordFilePath != null
                    ? Text(
                        "play",
                        style: TextStyle(color: Colors.red, fontSize: 20),
                      )
                    : Container(),
              ),
            ),
          ]),
        ),
      ),
    );
  }

  Future<bool> checkPermission() async {
    if (!await Permission.microphone.isGranted) {
      PermissionStatus status = await Permission.microphone.request();
      if (status != PermissionStatus.granted) {
        return false;
      }
    }
    return true;
  }

  void startRecord() async {
    bool hasPermission = await checkPermission();
    if (hasPermission) {
      statusText = "Recording...";
      recordFilePath = await getFilePath();
      isComplete = false;
      RecordMp3.instance.start(recordFilePath, (type) {
        statusText = "Record error--->$type";
        setState(() {});
      });
    } else {
      statusText = "No microphone permission";
    }
    setState(() {});
  }

  void pauseRecord() {
    if (RecordMp3.instance.status == RecordStatus.PAUSE) {
      bool s = RecordMp3.instance.resume();
      if (s) {
        statusText = "Recording...";
        setState(() {});
      }
    } else {
      bool s = RecordMp3.instance.pause();
      if (s) {
        statusText = "Recording pause...";
        setState(() {});
      }
    }
  }

  void stopRecord() {
    bool s = RecordMp3.instance.stop();
    if (s) {
      statusText = "Record complete";
      isComplete = true;
      setState(() {});
    }
  }

  void resumeRecord() {
    bool s = RecordMp3.instance.resume();
    if (s) {
      statusText = "Recording...";
      setState(() {});
    }
  }

  String recordFilePath;

  void play() {
    if (recordFilePath != null && File(recordFilePath).existsSync()) {
      AudioPlayer audioPlayer = AudioPlayer();
      audioPlayer.play(recordFilePath, isLocal: true);
    }
  }

  int i = 0;

  Future<String> getFilePath() async {
    Directory storageDirectory = await getApplicationDocumentsDirectory();
    String sdPath = storageDirectory.path + "/record";
    var d = Directory(sdPath);
    if (!d.existsSync()) {
      d.createSync(recursive: true);
    }
    return sdPath + "/test_${i++}.mp3";
  }
}

I want to call the VoiceCreate function when clicking on onPressed

voiceCreate.dart

import 'package:flutter/material.dart';
import 'main.dart';

class VoiceCreate extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        backgroundColor: Colors.blueGrey,
        body: Center(
          child: IconButton(
              icon: Icon(Icons.mic),
              color: Colors.white,
              iconSize: 70,
              onPressed: () {}),
        ),
      ),
    );
  }
}

I want to call startRecord method from main.dart when clicking on onPressed

2 answers

  • answered 2020-07-29 17:33 EdwynZN

    If you check the code of IconButton you'll see that onPressed is a VoidCallback, you can try to imitate the logic to do the same

    class VoiceCreate extends StatelessWidget {
      final VoidCallback onPressed;
      VoiceCreate({this.onPressed});
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            backgroundColor: Colors.blueGrey,
            body: Center(
              child: IconButton(
                  icon: Icon(Icons.mic),
                  color: Colors.white,
                  iconSize: 70,
                  onPressed: onPressed),
            ),
          ),
        );
      }
    }
    

    And in main just call your widget VoiceCreate with an onPressed parameter

    VoiceCreate(
      onPressed: () => startRecord
    )
    

    edited code here. Still the startRecord() is not working. VoiceCreate() is working

    floatingActionButton: FloatingActionButton(
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) {
                      return VoiceCreate(onPressed: () => startRecord);
                    }),
                  );
                },
                // Add your onPressed code here!
    
                child: Icon(Icons.add),
                backgroundColor: Colors.tealAccent.shade700,
              ),
    
    
    class VoiceCreate extends StatelessWidget {
      final VoidCallback onPressed;
      VoiceCreate({this.onPressed});
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            backgroundColor: Colors.blueGrey,
            body: Center(
              child: IconButton(
                  icon: Icon(Icons.mic),
                  color: Colors.white,
                  iconSize: 70,
                  onPressed: onPressed),
            ),
          ),
        );
      }
    }
    

  • answered 2020-07-29 17:35 Andrey Gritsay

    You could do this by using shared view model across need widgets, like so: I'd recommend to use this approach instead of callbacks and Stateful widgets

    import 'package:flutter/material.dart';
    import 'package:get/get.dart';
    
    class Parent extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return GetBuilder<CommonViewModel>(
          init: CommonViewModel(),
          builder: (model) {
            return Scaffold(
              body: Column(
                children: [
                  RaisedButton(onPressed: () => model.parentMethod(0)),
                  RaisedButton(onPressed: () => model.childMethod('call from parent')),
                ],
              ),
            );
          },
        );
      }
    }
    
    class Child extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return GetBuilder<CommonViewModel>(
          builder: (model) {
            return Scaffold(
              body: Column(
                children: [
                  RaisedButton(onPressed: () => model.childMethod('call from child')),
                  RaisedButton(onPressed: () => model.parentMethod(100)),
                ],
              ),
            );
          },
        );
      }
    }
    
    class CommonViewModel extends GetxController {
      void parentMethod(int argument) {
        print('Parent method $argument');
      }
    
      void childMethod(String argument) {
        print('Child method $argument');
      }
    }