通常,您不仅要导航到新屏幕,还要将数据传递到屏幕。例如,您可能想要传递有关已点击项目的信息。
在此示例中,创建一个待办事项列表。点击待办事项时,导航到显示有关记录的信息的新屏幕(小部件)。此配方使用以下步骤:
- 定义一个 RecordObject 类。
- 创建一个
StatefulWidget
. 我们称之为 RecordsScreen(用于:显示记录列表)。
- 创建可以显示有关记录的信息的详细信息屏幕。
- 导航并将数据传递到详细信息屏幕。
定义一个 RecordObject 类
class RecordsScreen extends StatefulWidget {
List<RecordObject> records;
RecordsScreen({Key key, @required this.records}) : super(key: key);
@override
_RecordsScreenState createState() => _RecordsScreenState();
}
class _RecordsScreenState extends State<RecordsScreen> {
@override
Widget build(BuildContext context) {
widget.records = List<RecordObject>.generate(20,
(i) => RecordObject(
'Record $i',
'A description of what needs to be done for Record $i',
),
);
return Scaffold(
appBar: AppBar(
title: Text('Records'),
),
body: ListView.builder(
itemCount: widget.records.length,
itemBuilder: (context, index) {
return ListTile(
title: Text( widget.records[index].title),
// When a user taps the ListTile, navigate to the DetailScreen.
// Notice that you're not only creating a DetailScreen, you're
// also passing the current todo through to it.
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DetailScreen(recordObject: widget.records[index]),
),
);
},
);
},
),
);
}
创建详细信息屏幕- 屏幕标题包含记录的标题,屏幕主体显示描述。
class DetailScreen extends StatefulWidget {
// Declare a field that holds the RecordObject.
final RecordObject recordObject;
// In the constructor, require a RecordObject.
DetailScreen({Key key, @required this.recordObject}) : super(key: key);
@override
_DetailScreenState createState() => _DetailScreenState();
}
class _DetailScreenState extends State<DetailScreen> {
@override
Widget build(BuildContext context) {
// Use the RecordObject to create the UI.
return Scaffold(
appBar: AppBar(
title: Text(widget.recordObject.title),
),
body: Padding(
padding: EdgeInsets.all(16.0),
child: Text(widget.recordObject.description),
),
);
}
}