Flutter的菜鸟教程十四:携带数据跳转页面

在上文中学习了简单的页面跳转,本文将在跳转中携带数据到下一个页面
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);
          },
        ),
      ),
    );
  }
}

这里写图片描述

跳转之后的页面获取了第一个页面携带的数据并显示出来

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值