如何为AnimatedContainer创建setState函数

时间:2019-01-17 14:41:14

标签: dart flutter

我已经创建了自定义的有状态小部件,并且使用了一个布尔值,用于检查AnimatedContainer的状态。另外,createState中有一个函数可以检查AnimatedContainer的状态并更改容器的宽度。我的问题是我在孩提时尝试使用AnimatedContainer中的函数_handleTap(),但它给我一个错误,表明该表达式具有void类型,因此无法使用。

class SectionTaps extends StatefulWidget {
  SectionTaps(this.isActive);

  bool isActive = false;

  _SectionTapsState createState() => _SectionTapsState();
}

class _SectionTapsState extends State<SectionTaps> {
 bool _isActive = false;
 double _width = 255.0;
  void _handleTap(){
   setState(() {
        _isActive = widget.isActive;
        _isActive == true ? _width = 55.0 : _width = 255.0;
        //change container width
      });
 }
 final leftButton = new AnimatedContainer(
    duration: Duration(seconds: 1),
    height: 88.0,
    width: 255.0,
    decoration: new BoxDecoration(
      color: new Color(0xFF376480),
      shape: BoxShape.rectangle,
      borderRadius: new BorderRadius.only(
        topRight: Radius.circular(80.0),
        bottomRight: Radius.circular(80.0),
      ),
      boxShadow: <BoxShadow>[
        new BoxShadow(  
          color: Colors.black12,
          blurRadius: 10.0,
          offset: new Offset(0.0, .0),
        ),
      ],
    ),
    child: _handleTap(),

 );

1 个答案:

答案 0 :(得分:0)

您需要用AnimatedContainer将-GestureDetector换行并使用onTap:来调用setSate()。

代码:

class SectionTaps extends StatefulWidget {
  SectionTaps(this.isActive);

  bool isActive = false;

  _SectionTapsState createState() => _SectionTapsState();
}

class _SectionTapsState extends State<SectionTaps> {
  bool _isActive = false;
  double _width = 255.0;
  void _handleTap() {
    setState(() {
        print ('Set State Called.');
      _isActive = widget.isActive;
      _isActive == true ? _width = 55.0 : _width = 255.0;
      //change container width
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Center(
        child: GestureDetector(
          onTap: () {
            _handleTap();
          },
          child: new AnimatedContainer(
            duration: Duration(seconds: 1),
            height: 88.0,
            width: 255.0,
            decoration: new BoxDecoration(
              color: new Color(0xFF376480),
              shape: BoxShape.rectangle,
              borderRadius: new BorderRadius.only(
                topRight: Radius.circular(80.0),
                bottomRight: Radius.circular(80.0),
              ),
              boxShadow: <BoxShadow>[
                new BoxShadow(
                  color: Colors.black12,
                  blurRadius: 10.0,
                  offset: new Offset(0.0, .0),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}