按下图标按钮时如何打开容器?

时间:2018-12-10 08:43:42

标签: dart flutter

我想要一个可以在按下按钮时打开颜色容器的应用。

这是主页:

class MainPage extends StatefulWidget {

  @override
    MainPageState createState() => MainPageState();

}

class MainPageState extends State<MainPage> {

  @override
    Widget build(BuildContext context) {
      return MaterialApp (
        debugShowCheckedModeBanner: false,
        home: Scaffold (
          body: Material (
            color: Colors.black
            child: Center (
              child: IconButton (
                onPressed: () {},
                icon: Icon (
                  Icons.add,
                  color: Colors.white, 
                ),
                iconSize: 40.0,
              )
            ),
          ),
        ),
      );
    }

}

这是那个容器:

class ColoredContainer extends StatelessWidget {

  @override
    Widget build(BuildContext context) {
      return Center (
        child: Container (
          color: Colors.white,
          height: 500.0,
          width: 300.0
        )
      );
    }

}

按下按钮时是否可以打开容器?当容器弹出时,是否也可以制作动画?如果可以,那么如何添加动画?

1 个答案:

答案 0 :(得分:1)

您可以尝试类似的方法。对于动画-尝试使用AnimatedContainer代替Container

class MainPageState extends State<MainPage> {
  bool _isContainerVisible = false;

  @override
    Widget build(BuildContext context) {
      return MaterialApp (
        debugShowCheckedModeBanner: false,
        home: Scaffold (
          body: Material (
            color: Colors.black,
            child: Column(
              children: <Widget>[
                IconButton(
                  onPressed: () {
                    setState(() {
                      _isContainerVisible = !_isContainerVisible;
                    });
                  },
                  icon: Icon(
                    Icons.add,
                    color: Colors.white,
                  ),
                  iconSize: 40.0,
                ),
                ColoredContainer(_isContainerVisible)
              ],
            ),
          ),
        ),
      );
    }

}

class ColoredContainer extends StatelessWidget {
  ColoredContainer(this._isContainerVisible);
  final bool _isContainerVisible;

  @override
    Widget build(BuildContext context) {
      return Center (
        child: AnimatedContainer (
          duration: Duration(seconds: 1),
          color: Colors.white,
          height: _isContainerVisible ? 500.0 : 0.0,
          width: _isContainerVisible ? 300.0 : 0.0
        )
      );
    }

}