Search code examples
flutterstatefulwidget

Getting error while passing key in stateful widget flutter


I'm trying to animate the width of AnimatedContainer. For this purpose i'm using a statefull widget in external file, here is code for this class

class AnimatedContainerWidget extends StatefulWidget {
const AnimatedContainerWidget({
    Key: key,
  }) : super(key: key);
  @override
  _AnimatedContainerWidgetState createState() =>
      _AnimatedContainerWidgetState();
}

class _AnimatedContainerWidgetState extends State<AnimatedContainerWidget> {
  double _height = 100.0;
  double _width = 100.0;
  _increaseWidth() {
    setState(() {
      _width = _width >= 300 ? 100.0 : _width += 50.0;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: <Widget>[
        AnimatedContainer(
          duration: Duration(milliseconds: 500),
          curve: Curves.elasticInOut,
          color: Colors.amber,
          height: _height,
          width: _width,
          child: FlatButton(
            child: Text('Tap to grow width\n $_width'),
            onPressed: _increaseWidth(),
          ),
        )
      ],
    );
  }
}

But i'm getting error saying "getter not found for 'key' "

lib/widgets/animated_container.dart:5:10: Error: Getter not found: 'key'.
    Key: key,                                                           
         ^^^                                                            
lib/widgets/animated_container.dart:6:19: Error: Getter not found: 'key'.
  }) : super(key: key);                                                 
                  ^^^                                                   
                                                                        
                                                                        
FAILURE: Build failed with an exception. 

Solution

  • There is a colon in the constructor that you need to remove.

    const AnimatedContainerWidget({
        Key key, // Replace "Key: key" with "Key key"
    }) : super(key: key);