我是 Flutter 和编程的新手。我正在尝试使用 ListViewBuilder 创建一个列表视图(卡片)以显示“页面标题”相应的命名路由以导航到该页面。目前我能够从列表中生成“页面标题”。但我无法生成路线。怎么可能呢?我在下面添加了我的代码:
import 'package:flutter/material.dart';
import 'page1.dart';
import 'page2.dart';
import 'page3.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Learning Flutter',
theme: ThemeData(
primarySwatch: Colors.cyan,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
List<String> contentList = [
'open page 1',
'open page 2',
'open page 3',
];
List<Route> myRoute = [
//I want to add the list of pages here
];
return Scaffold(
appBar: AppBar(
title: Text('Learning Flutter'),
centerTitle: true,
),
body: ListView.builder(
itemCount: contentList.length,
itemBuilder: (context, index) {
return Card(
child: ListTile(
leading: CircleAvatar(
backgroundImage: AssetImage('images/ic_launcher_round.png'),
),
title: Text(contentList[index]),
trailing: Icon(Icons.arrow_forward),
onTap: () {
//I want to add the route dynamically based on the List index
},
),
);
},
),
);
} }
答案 0 :(得分:1)
List<Route> myRoute = [
"MaterialPageRoute(builder: (_) => Page1() )",
"MaterialPageRoute(builder: (_) => Page2() )",
"MaterialPageRoute(builder: (_) => Page3() )",
];
和
onTap: () {
Navigator.of(context).push(myRoute[index]);
},
这应该有效。
但我建议以后使用命名路由,并使用 .pushNamed("routeName"); 您可以在每个页面中定义一个路由名称,例如在 Page1() 中:
s
tatic final routeName "/page1";
然后调用
Navigator.of(context).pushNamed(Page1.routeName);
所以如果你想用你的代码做到这一点,你可以拥有:
List<String> routes= [
Page1.routeName,
Page2.routeName,
Page3.routeName,
];
和
onTap: () {
Navigator.of(context).pushNamed(routes[index]);
},