简体   繁体   English

如何从父级调用另一个小部件的子方法

[英]How to call child method from parent for another widget

main.dart主要.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单击 onPressed 时,我想调用VoiceCreate function

voiceCreate.dart 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单击onPressed时,我想从 main.dart 调用startRecord方法

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如果你检查 IconButton 的代码,你会看到 onPressed 是一个 VoidCallback,你可以尝试模仿逻辑来做同样的事情

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在主要的情况下,只需使用 onPressed 参数调用您的小部件VoiceCreate

VoiceCreate(
  onPressed: () => startRecord
)

edited code here.在这里编辑代码。 Still the startRecord() is not working. startRecord()仍然不工作。 VoiceCreate() is working VoiceCreate()正在工作

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),
        ),
      ),
    );
  }
}

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您可以通过跨需要的小部件使用共享视图 model 来做到这一点,如下所示:我建议使用这种方法而不是回调和有状态小部件

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');
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Flutter - 如何从父级调用子级小部件的方法 - Flutter - how to call child widget's method from parent 如何从父小部件调用子小部件的 setState? - How can I call setState of a child widget from a parent widget? 如何从子小部件调用父小部件中的 function | Flutter - How to Call a function in parent widget from child widget | Flutter 如何从父小部件调用子小部件 function - how to call child widget function from parent widget 如何从 Flutter 中的子小部件调用父小部件 function - How to call parent widget function from child widget in Flutter 如何在flutter中从父小部件调用子小部件的initState()方法 - How to Invoke initState() method of child widget from parent widget in flutter 如何从另一个有状态小部件调用一个有状态小部件中的方法 - how to Call method in one stateful widget from another stateful widget 从另一个小部件调用小部件的方法 - Call method of a widget from another widget 如何从无状态父小部件调用有状态子小部件的状态函数? - How to call state functions of a stateful child widget from a stateless parent widget? Flutter - 如何从子小部件调用父小部件函数,同时还使用变量保持状态? - Flutter - How do I call a Parent widget function from child widget while also maintaining the state with a variable?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM