Flutter使用aligned_dialog遇builder参数类型错误,求解决及原因
问题原因与修复方案
错误原因
你遇到的类型错误和StatelessWidget无关,核心问题是**showAlignedDialog的builder参数传错了类型**:
builder要求的是一个接收BuildContext并返回Widget的函数(类型为Widget Function(BuildContext))- 你直接传了
context(BuildContext对象),两者类型不匹配,所以触发报错,用this.context也没用,因为它本质还是BuildContext类型。
修复方法
把builder改成一个返回弹窗内容的函数,比如返回AlertDialog或自定义弹窗组件:
修改后的代码示例:
GestureDetector( onTap: (){ showAlignedDialog( context: context, // 这里改成函数形式,返回你要展示的弹窗内容 builder: (context) => AlertDialog( title: const Text('提示'), content: const Text('这是aligned_dialog展示的弹窗'), actions: [ TextButton( onPressed: () => Navigator.pop(context), child: const Text('关闭'), ) ], ), followerAnchor: Alignment.topLeft, targetAnchor: Alignment.bottomRight, barrierColor: Colors.transparent, avoidOverflow: true, ); }, child: Container( width: 20, height: 20, child: SvgPicture.asset( 'assets/logo/Information.svg', ), ), ),
如果需要自定义弹窗样式,也可以把builder里的内容换成你自己写的Widget组件,只要保证是(BuildContext) => Widget的形式即可。
内容的提问来源于stack exchange,提问作者Kim San
相关产品推荐
相关产品推荐

