flutter - type '(String) => dynamic' 不是 'Widget' 类型的子类型
问题描述
我正在尝试使用命名路由导航到页面。
主文件中的路由:
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'FlutterShare',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.deepPurple,
accentColor: Colors.teal,
),
home: Home(),
routes: {
'/search': (BuildContext context) => Search(),
},
);
}
}
推送到页面:
class HomeScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text('BookClub'),
actions: [
IconButton(
icon: Icon(Icons.add),
onPressed: () {
Navigator.of(context).pushNamed('/search');
})
],
),
drawer: AppDrawer(),
);
}
}
错误:
type '(String) => dynamic' is not a subtype of type 'Widget'
The relevant error-causing widget was
Search lib\main.dart:21
这是我第一次构建应用程序,但我没有得到解决方案。错误出现在 main.dart 文件中的路由中。
搜索代码:
class Search extends StatefulWidget {
@override
_SearchState createState() => _SearchState();
}
class _SearchState extends State<Search> {
TextEditingController searchController = TextEditingController();
Future<QuerySnapshot> searchResultsFuture;
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Theme.of(context).primaryColor.withOpacity(0.8),
appBar: buildSearchField(),
body: buildNoContent()
);
}
}
AppBar buildSearchField() {
return AppBar(
backgroundColor: Colors.white,
title: TextFormField(
controller: searchController,
decoration: InputDecoration(
hintText: "Search for a book",
filled: true,
prefixIcon: Icon(
Icons.account_box,
size: 28.0,
),
suffixIcon: IconButton(
icon: Icon(Icons.clear),
onPressed: null,
),
),
onFieldSubmitted: null,
),
);
}
Container buildNoContent() {
final Orientation orientation = MediaQuery.of(context).orientation;
return Container(
child: Center(
child: ListView(
shrinkWrap: true,
children: <Widget>[
SvgPicture.asset(
'assets/images/search.svg',
height: orientation == Orientation.portrait ? 300.0 : 200.0,
),
Text(
"Find Users",
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.white,
fontStyle: FontStyle.italic,
fontWeight: FontWeight.w600,
fontSize: 60.0,
),
),
],
),
),
);
}
希望这会有所帮助。从过去的 3 个小时开始,我一直被困在这个问题上,找不到任何解决这个问题的方法。
解决方案
main.dart. 您必须将起始页添加到 initialRoute。您可以删除“home”参数。
initialRoute: HomeScreen(),
routes: {
"/search" (context) => Search()
},
所以,home.dart 文件在里面;
Navigator.of(context).pushNamed('/search');
推荐阅读
- python - TypeError:需要一个类似字节的对象,而不是 Python 中 Image 命令的“str”
- angular - 如何使垫表行拖放与 cdkDragHandle 一起使用,以便只能使用句柄拖动行?
- docker - Docker 文件夹权限 - Tar 错误 - 权限错误
- angularjs - Ionic v3 polyfill.js 未捕获的承诺错误
- wordpress - 在 Wordpress 中安装 Google 标记管理器(无需编写 PHP 主题)
- c++ - 模板具有默认参数时省略尖括号
- python - 有人可以解释一下使用 matplotlib 创建雷达图的代码吗
- python - TKinter 中带有多个小部件的滚动条
- angular - 带有signalR的角度:多个集线器连接到同一条路线
- jenkins - ws() 如何在 Jenkins groovy 中工作?