簡體   English   中英

如何在另一個有狀態小部件中調用 Void() function

[英]How to call Void() function in another Stateful widget

我想在另一個有狀態小部件中調用 void play() 方法

main.dart

    import 'dart:io';
import 'package:audioplayer/audioplayer.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.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';
import 'stopwatch.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 StopWatch();
                        },
                      ),
                    );
                  },
                ),
                ListTile(
                  title: Text('Sign in'),
                  onTap: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) {
                          return LoginScreen();
                        },
                      ),
                    );
                    // add sign in page
                  },
                ),
              ],
            ),
          ),
          floatingActionButton: FloatingActionButton(
            onPressed: () {
              Navigator.push(
                context,
                MaterialPageRoute(builder: (context) {
                  return MyHomePage();
                }),
              );
            },
            // 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(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              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; //maybe**strong text** this need to take

  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";
  }
}

voiceCreate.dart我想在onPressed時調用這里

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  var _isRecording = false;

MyHomePage.play()**//getting error here** 

  _startRecording() {
    this.setState(() {
      _isRecording = true;
    });
  }

  _stopRecording() {
    this.setState(() {
      _isRecording = false;
    });
  }

@override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        backgroundColor: Colors.white,
        body: Center(
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              IconButton(
                icon: Icon(Icons.mic),
                color: Colors.black,
                iconSize: 70,
                onPressed: () => _startRecording(),
              ),
              IconButton(
                icon: Icon(Icons.stop),
                color: Colors.black,
                iconSize: 70,
                onPressed: () => _stopRecording(),
              ),
              IconButton(
                  icon: Icon(Icons.play_arrow),
                  color: Colors.black,
                  onPressed: () => `MyHomePage(title: "My title", play: this.play()),`**// getting error here**
              ),

已經調用了starRecordingstopRecording

當 onPressed 時所有三個功能都不起作用,它們是 startRecording、stopRecording 和 play。 這些 function 在 main.dart 中工作正常,但在 voiceCreate.dart 中沒有

Dart 函數是一流的,這意味着您可以像變量一樣傳遞它們。 在您的小部件 class 上有一個VoidCallback成員。

MyHomePage(this.playCallback, {Key key, this.title}) : super(key: key);
  final String title;
  final VoidCallback playCallback;

您可以在構造函數中傳遞它。

child: MyHomePage(play)

然后你可以在你的 state object 中找到它。

class _MyHomePageState extends State<MyHomePage> {
    ...

    onPressed: widget.playCallback

    ...    
}

警告

這不是實現此目的的推薦方法。 如果可能,小部件必須包含零業務邏輯。 像這個答案這樣的小技巧會讓你的代碼變得非常復雜。 考慮閱讀state 管理解決方案。

答案 3.0

根據您顯示的完整代碼,這里是僅根據您的代碼的解決方案。 我相信它會為你消除一些困惑。

  • play()從您的FloatingActionButton中的main.dart正確傳遞到您的MyHomePage 我沒有使用main.dart的完整代碼,但特別是您要移至MyHomePage的部分

main.dart

           floatingActionButton: FloatingActionButton(
            onPressed: () {
              Navigator.push(
                context,
                MaterialPageRoute(builder: (context) {
                  // you need to pass two positional arguments
                  // since your MyHomePage accepts two arguments
                  // one is your title and one is your function
                  return MyHomePage(title: "My Title", play: play);
                }),
              );
            }
  • 其次,使用您的方法在MyHomePage構造函數中傳遞。 這將保持原樣。 只需查看此處代碼的最后一行,看看我們如何使用main.dart中傳遞的play()方法
class MyHomePage extends StatefulWidget {
  // accepting the method in the constructor
  // so you can pass it with the title from your main.dart
  MyHomePage({Key key, this.title, this.play}) : super(key: key);
  
  final String title;
  final Function play; // this is the function
  
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

現在如何在您的 Class 中使用它

class _MyHomePageState extends State<MyHomePage> {
  var _isRecording = false;

  _startRecording() {
    this.setState(() {
      _isRecording = true;
    });
  }

  _stopRecording() {
    this.setState(() {
      _isRecording = false;
    });
  }

@override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        backgroundColor: Colors.white,
        body: Center(
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              IconButton(
                icon: Icon(Icons.mic),
                color: Colors.black,
                iconSize: 70,
                onPressed: () => _startRecording(),
              ),
              IconButton(
                icon: Icon(Icons.stop),
                color: Colors.black,
                iconSize: 70,
                onPressed: () => _stopRecording(),
              ),
              IconButton(
                  icon: Icon(Icons.play_arrow),
                  color: Colors.black,
                  onPressed: () => widget.play() // call like this
              )

注意:請同時查看我代碼中的注釋

現在檢查這是否適合您。 這應該可以解決您的問題。

我認為其他 2 個讓您大致了解如何按照您想要的方式進行操作。 使用這些方法沒有任何問題。 它們將起作用,除非當導航開始變得有點復雜時,您將開始使用更多頁面並且您可能需要繼續將其傳遞到樹中。

所以像easeccy提到的更多地關注state管理。 Blocs , Redux 之類的東西都非常有幫助。 原因就像 flutter 如何根據 setstate() 構建事物一樣,state 管理類允許您在不同的地方添加相同的事件,只要它們屬於相同的實例。 所有的建築商都將根據他們生產的 state 進行重建。

例如,對於 Blocs,如果您要向 bloc 添加一個 play 事件。 無論您身在何處,只要您能夠向頁面提供塊,您就可以添加事件和屏幕上的任何內容(如果您要構建多個 dart 文件)都將根據您的 state 進行重建會產生。

bloc main.dart 示例

void main() async{

  runApp(
    //Having this before return MaterialApp() ensures that you can call it 
    //anywhere in the app below this tree
    BlocProvider<TheTypeOfBloc>(
      create: (context) => TheTypeOfBloc(),
      child: App(),
  )

}

您擁有的任何其他小部件/構建

 @override
  Widget build(BuildContext context) {
    return BlocListener<TheTypeOfBloc,TheTypeOfState>(
     listener : (context,state){
     //tldr of listen =  when your state change do something.
     //so your void function can be call here
          if(state is playState){
             _play();
          }
     }
     child:BlocBuilder<TheTypeOfBloc,TheTypeOfState> (
    // basically anything below here gets rebuild when you change a state.
      builder: (context,state) {
         return //what you want to build here like listener based on the 
                //state or just build normally without the builder.
      }
     ),
    );
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM