子类widget回调父类方法报错,如何解决?

官网url:https://flutterchina.club/tut...

参考官网代码示例写了一段运行,但回调父类方法是报了如下错误:

clipboard.png

完全参考示例实现,出错后也查询了很多网站,但都没有找到有用的方法。

相关代码

class ParentWidget extends StatefulWidget {
  @override
  _ParentWidgetState createState () => new _ParentWidgetState();
}

class _ParentWidgetState extends State<ParentWidget> {
  bool _active = false;

  void _handleTapboxChanged(bool newValue) {
    setState(() {
     _active = newValue; 
    });
  }

  @override
  Widget build(BuildContext context) {
    return new Container(
      child: new TapboxB(
        active: _active,
        onChanged: _handleTapboxChanged,
      ),
    );
  }
}

// --------------------- TapboxB ---------------------
class TapboxB extends StatelessWidget  {
  TapboxB({Key key, this.active: true, @required this.onChanged}) : super(key: key);
  
  final bool active;
  final ValueChanged<bool> onChanged;

  void _handleTap() {
    onChanged(!active);
  }

  Widget build(BuildContext context) {
    return new GestureDetector(
      onTap: _handleTap,
      child: new Container(
        child: new Center(
          child: new Text(
            active ? 'Active' : 'Inactive',
            style: new TextStyle(fontSize: 32.0, color: Colors.white)
          ),
        ),
        width: 200.0,
        height: 200.0,
        decoration: new BoxDecoration(
          color: active ? Colors.lightGreen[700] : Colors.grey[600]
        ),
      ),
    );
  }
}

代码本身没有报语法或编译错误,但在点击触发_handleTap的时候就报错了,希望前辈们能教导下错在哪里了,感谢

阅读 1.8k
1 个回答

我觉得写的没问题,尝试重新编译或重装环境


要么试试这样

if(onChanged!=null){
onChanged(!active);
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题