在上文中学习了简单的页面跳转,本文将在跳转中携带数据到下一个页面
2.跳转到下一个页面并携带数据
import 'package:flutter/material.dart';
import 'package:meta/meta.dart';
final todos = new List<Todo>.generate(
20,
(i) => new Todo(
"Todo $i", "A description of what needs to be done for Todo $i"));
/**
* 跳转到新页面并携带数据
*/
void main() {
runApp(new MaterialApp(
title: "Flutter",
home: new FirstScreen(todos),
));
}
class Todo {
final String title;
final String description;
Todo(this.title, this.description);
}
/**
* 第一个页面
*/
class FirstScreen extends StatelessWidget {
final List<Todo> todos;
FirstScreen(this.todos);
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("First Screen"),
),
body: new Center(
child: new ListView.builder(
itemCount: todos.length,
itemBuilder: (context, index) {
return new ListTile(
title: new Text(todos[index].title),
//item的点击事件 跳转到新的页面并携带一个Todo对象 传参就是通过构造函数了
onTap: () {
Navigator.push(
context,
new MaterialPageRoute(
builder: (context) =>
new DetailScreen(todo: todos[index])));
},
);
}),
),
);
}
}
/**
* 第二个页面
*/
class DetailScreen extends StatelessWidget {
final Todo todo;
DetailScreen({Key key, @required this.todo}) : super(key: key);
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("${todo.title}"),
),
body: new Center(
child: new GestureDetector(
child: new Text("${todo.description}"),
onTap: () {
Navigator.pop(context);
},
),
),
);
}
}
跳转之后的页面获取了第一个页面携带的数据并显示出来