Flutter: Call a function on a child widget's state

后端 未结 4 1673
小蘑菇
小蘑菇 2021-02-04 06:40

I\'ve created a stateful widget and its parent widget needs to call a function that lives in the child\'s state.

Specifically, I have a class PlayerContainer that create

4条回答
  •  北恋
    北恋 (楼主)
    2021-02-04 07:12

    I know that I'm pretty late to the party, but I have something that I think might help. So, you need to do four (4) things in your VideoPlayerController class:
    1. Create an instance of your state class.
    2. Create a method (play) which will be accessible in your PlayerContainer class
    3. In your method, use the VideoPlayerControllerState instance to call the method in your state class.
    4. Finally, when you createState, do so using the instance that you already created.

    class VideoPlayerController extends StatefulWidget {
      final VideoPlayerControllerState vpcs = VideoPlayerControllerState();
    
      void play() {
        vpcs.play();
      }
    
      @override
      State createState() => vpcs;
    }
    

    As you see, the play method uses vpcs (the VideoPlayerControllerState instance) to call the play method already in your state class.

    In your PlayerContainer class, use your member variable to call the play method.

    class PlayerContainerState extends State {
      VideoPlayerController _vpc;
    
      @override
      void initState() {
        super.initState();
        _vpc = VideoPlayerController();
      }
      ...
    
      void _handlePressPlay(){
        _vpc.play();
      } 
      ...
    
      @override
      Widget build(BuildContext context) {
        return ... //your video player widget using _vpc as your VideoPlayerController
          _vpc,
        );
      }
    }
    

    You can call _handlePressPlay() from the onPressed method of your play button. Alternatively, just put _vpc.play() in the onPressed method. Your choice :-).

提交回复
热议问题