Flutter开发聊天应用报错:参数类型Widget无法分配,如何解决?
参数类型 'Widget' 不能分配给对应参数类型
问题原因
Scaffold组件的appBar参数要求接收的是PreferredSizeWidget类型的组件,你自定义的AppBarMain方法返回值声明为Widget,虽然方法内部实际返回的AppBar本身已经实现了PreferredSizeWidget接口,但Dart静态类型校验会因为返回值声明不匹配抛出类型错误。你收到的“涉及PreferredSizeWidget”的提示是框架参数本身的类型约束,并非你自己的代码定义了该类型。
解决方案
修改公共组件文件中AppBarMain方法的返回值类型即可,修改后的代码如下:
import 'package:flutter/material.dart'; // 仅修改该行的返回类型即可,其余代码不变 PreferredSizeWidget AppBarMain(BuildContext context) { return AppBar( title: Image.asset( "assets/images/logo.png", height: 50, ), ); } InputDecoration textFieldInputDecoration(String hintText) { return InputDecoration( hintText: hintText, hintStyle: TextStyle(color: Colors.white), focusedBorder: UnderlineInputBorder( borderSide: BorderSide(color: Colors.white), ), enabledBorder: UnderlineInputBorder( borderSide: BorderSide(color: Colors.white), ), ); } TextStyle simpleTextStyle() { return TextStyle(color: Colors.white, fontSize: 16); }
修改后重新编译项目即可解决该报错。
内容的提问来源于stack exchange,提问作者Giorgino Romagnolo
相关产品推荐
相关产品推荐

