我如何公开StatefulWidget的方法?

时间:2017-07-25 11:42:10

标签: dart flutter

假设我想构建一个名为MySlideWidget的StatefulWidget,它提供一个公共实例方法:animate()

当我按下MySlideWidget的父级按钮时,我可以调用MySlideWidget的{​​{1}}方法来触发animate()的内部SlideTransition

用法如下:

MySlideWidget

我想知道如何在class MySlideWidgetDemo extends StatelessWidget { @override Widget build(BuildContext context) { MySlideWidget mySlideWidget = new MySlideWidget(); return new Scaffold( body: mySlideWidget, floatingActionButton: new FloatingActionButton( onPressed: () { mySlideWidget.animate(); }, tooltip: 'Start', child: new Icon(Icons.add), )); } } 内封装AnimationController_controller.forward()的实现,因此MySlideWidget的用户可以简单地调用MySlideWidget

这可能吗?或者在Flutter中进行封装的想法是什么?

1 个答案:

答案 0 :(得分:1)

您应该使用AnimationController并将其传递给SlideTransition。然后在需要时拨打controller.forward()

以下是样本:

    class _MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin {

  AnimationController _controller;
  Animation<FractionalOffset> _slideTransitionPosition;

  @override
  initState() {
    super.initState();

    _controller = new AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 2000),
    );

    _slideTransitionPosition = new FractionalOffsetTween(
      begin: const FractionalOffset(0.0, -1.0),
      end: const FractionalOffset(0.0, 10.0),
    ).animate(new CurvedAnimation(
      parent: _controller,
      curve: Curves.fastOutSlowIn,
    ));
  }

  void _onPress() {
    _controller.forward();
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: new Container(
        child: new SlideTransition(
          position: _slideTransitionPosition,
          child: new Container(
            color: Colors.red,
            width: 100.0,
            height: 100.0,
          ),
        ),
      ),
      floatingActionButton: new FloatingActionButton(
        onPressed: _onPress,
        tooltip: 'Start',
        child: new Icon(Icons.add),
      ),
    );
  }
}

您也可以在demos

中找到示例