简体   繁体   中英

How to call a method in another stateful widget

I am building a podcasting type app, so need to call the record, stop, and play functions in many places, I created the methods, but difficulty to call these methods in other places.

main.dart

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

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

void startRecord() //Need to call all of these method in coming stateful widgets         
void stopRecord() //
void pauseRecord()//
void resumeRecord()//
void play() //

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

      //more code is here 

Expanded(
            child: GestureDetector(
              child: IconButton(
                  icon: Icon(Icons.mic),
                  color: Colors.white,
                  iconSize: 40,
                  onPressed: () async {
                    startRecord();
                  }),
            ),
          ),



}



class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(


onPressed: () {
startRecord()

// need to call the method here. 

}

Pressed: () {
    stopRecord()

// need to call the method here. 

}

Pressed: () {
    play()

// need to call the method here. 

}

),
}

Need to call all the methods from a first stateful widget for bottom stateful widgets

also, need to call these methods for other classes when code progress

both stateful widgets are in the main.dart. I could not call the method from the first class for the second stateful widget

You can get the state of a parent widget using the BuildContext of the child widget like so:

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
  
  static _MyAppState of(BuildContext context) {
    return context.findAncestorStateOfType<_MyAppState>();
  }
}

class _MyAppState extends State<MyApp> {
  String statusText = "";
  bool isComplete = false;
  
  void startRecord() {
    print('Hello');
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    MyApp.of(context).startRecord();
    
    return Scaffold(
      body: Placeholder(),
    );
  }
}

This is not a rocket science, just a simple line of code, and you are done.

What you have to do, is to just call the MyHomePage() and let it accept the startRecording() to be used inside the Widget

1. Passing the data from MyApp() to MyHomePage()

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // here you pass the your function
      home: MyHomePage(onPressed: startRecording)
    );
  }

2. Receiving the data in MyHomePage()

class MyHomePage extends StatefulWidget {
  // let it accept a function type onPressed argument
  final Function onPressed;
  
  // constructor
  MyHomePage({Key key, this.onPressed}): super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(

    // simply call the onPressed which received your startRecording() from MyApp
    onPressed: () => widget.onPressed()
}

Simply define that function outside the class as a stand-alone function like this But if you want to call from inside the class. Heres the code.

inside a different class as a static function:

onPressed: () {
          _MyAppState().startRecord(); //call using the class name.
        }

Like this inside your onpressed Statement .

Should work.

Or else what you can do is define the function outside the class. Then use it where ever you want. Like this:

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


void startRecord(){
   .
   .
   .
}           /// Like here outside the class

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(.....



}



class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(


onPressed: () {
 startRecord();       // call Here as follows.
 }),
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM