颤振-使用onTap和列表调用



我知道有点乱的代码。

试图让onTap使用categoreslist切换到另一个页面,但得到错误的"返回类型'String'不是'Widget',正如闭包的上下文所要求的。"不太确定下面的代码应该是什么

List<Category> categoriesList = [
Category(name: "nameA", image: "imageA.png", page: "page1"),
Category(name: "nameB", image: "imageB.png", page: "page2"),
Category(name: "nameC", image: "imageC.png", page: "page3"),
Category(name: "nameD", image: "imageD.png", page: "page4"),
Category(name: "nameE", image: "imageE.png", page: "page5"),
Category(name: "nameF", image: "imageF.png", page: "page6"),
];
child: Padding(
padding: EdgeInsets.all(4.0),
child: GestureDetector(
onTap: (){
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => categoriesList[index].page));
},
child: Image.asset(
"assets/images/${categoriesList[index].image}",
width: 100,
height: 100,
),
),
),

主要。飞镖文件

import 'package:app/screens/page1.dart';
import 'package:app/screens/page2.dart';
import 'package:app/screens/home.dart';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
initialRoute: '/',
routes: {
'/': (context) => page1(),
'/second' : (context) => page2(),
},
title: 'My App',
theme: ThemeData(appBarTheme: AppBarTheme(color:Colors.blue, centerTitle: true)
),
home: Home(),
debugShowCheckedModeBanner: false,
);
}
}

问题是,当你应该传递一个Widget时,你正在传递一个String:

Navigator.push(
context,
MaterialPageRoute(
builder: (context) => categoriesList[index].page1));

builder: (context) =>(指数)categoriesList .page1));

这里的Builder需要一个Widget,例如MyPage1(categoriesList[index]),而不是一个String。如果你想导航,使用String作为RouteName,你应该使用类似

这样的内容。
Navigator.pushNamed(
context,
categoriesList[index].page);

列表中的名称必须与main.dart中的路由匹配,例如:

清单

Category(name: "nameA", image: "imageA.png", page: "/page1"),
Category(name: "nameB", image: "imageB.png", page: "/page2"),
Category(name: "nameC", image: "imageC.png", page: "/page3"),
...

和main.dart中的Routes

routes: {
...
'/page1': (context) => page1(),
'/page2' : (context) => page2(),
'/page3':(context) => page3(),...
},

相关内容

  • 没有找到相关文章

最新更新