Flutter使用Provider5时Consumer报错Object?无法赋值给String如何解决
问题解决方法
报错根源
你遇到的报错The argument type 'Object?' can't be assigned to the parameter type 'String'是因为使用Consumer时没有声明要监听的状态类型,Consumer默认将获取到的状态推断为Object?类型,和Text组件需要的String参数类型不匹配,所以即使加空安全运算符也无法解决类型不匹配的问题。
正确的Consumer写法
只需要给Consumer加上泛型约束,明确指定你要监听的状态为String类型即可:
Consumer<String>( builder: (context, title, child) { return Text( title, style: TextStyle(color: Colors.white), ); }, ),
如果你的Provider提供的是可空的String?类型,就对应修改泛型为String?,同时给Text组件设置默认值处理空情况即可:
Consumer<String?>( builder: (context, title, child) { return Text( title ?? '默认标题', style: TextStyle(color: Colors.white), ); }, ),
内容的提问来源于stack exchange,提问作者delaram
相关产品推荐
相关产品推荐

