Flutter学习 — 给新页面传值
2023-09-14 09:04:26 时间
效果图一:
点击跳转
效果图二:
点击第四项后并传值到下一个页面来显示
代码+注释:
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
/**
* 定义主页。
添加一个打开选择页面的按钮。
在选择页面上显示两个按钮。
点击一个按钮时,关闭选择的页面。
主页上弹出一个snackbar以显示用户的选择。
*/
class Todo {
final String title;
final String description;
Todo(this.title, this.description);
}
void main() {
runApp(new MaterialApp(
title: 'Passing Data',
home: new TodosScreen(
todos: new List.generate(
20,
(i) => new Todo(
'Todo $i',
'A description of what needs to be done for Todo $i',
),
),
),
));
}
class TodosScreen extends StatelessWidget {
final List<Todo> todos;
TodosScreen({Key key, @required this.todos}) : super(key: key);
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('Todos'),
),
body: new ListView.builder(
itemCount: todos.length,
itemBuilder: (context, index) {
return new ListTile(
title: new Text(todos[index].title),
// When a user taps on the ListTile, navigate to the DetailScreen.
// Notice that we're not only creating a new DetailScreen, we're
// also passing the current todo through to it!
/**
*当用户点击ListTile时,导航到DetailScreen。请注意,我们不仅在创建新的DetailScreen,而且还在传递当前的待办事项!
*/
onTap: () {
Navigator.push(
context,
new MaterialPageRoute(
builder: (context) => new DetailScreen(todo: todos[index]), //传入Todo对象
),
);
},
);
},
),
);
}
}
class DetailScreen extends StatelessWidget {
// Declare a field that holds the Todo
final Todo todo; //接收Todo 对象
// In the constructor, require a Todo
DetailScreen({Key key, @required this.todo}) : super(key: key);
@override
Widget build(BuildContext context) {
// Use the Todo to create our UI
return new Scaffold(
appBar: new AppBar(
title: new Text("${todo.title}"),
),
body: new Padding(
padding: new EdgeInsets.all(16.0),
child: new Text('${todo.description}'),
),
);
}
}
喜欢记得点个赞哟,我是王睿,很高兴认识大家!
更多原理请参考谷歌官网:给新页面传值
相关文章
- flutter画布绘制图片和文字
- Flet-基于Flutter的Python跨平台开发框架(组件学习)
- 几款设计精美的常用的Flutter应用程序模板
- 【Flutter 异步编程 - 拾】 | 探索 Stream 的转换原理与拓展
- flutter 报错解决
- Flutter 3.7 新特性:介绍后台isolate通道
- Flutter 组件集录 | 3.7 新增 - ContextMenu 菜单
- 【Flutter】Dart 面向对象 ( 类定义 | 类的继承 | 私有变量 | 可选参数 | 默认参数 | 初始化列表 )
- 【错误记录】Flutter 环境安装相关问题 ( 执行 flutter doctor 命令后续错误处理 )
- 【错误记录】Flutter 插件不兼容 ( requires Flutter SDK version >=1.22.0 <2.0.0, url_launcher >=5.7.7 <6.0.0- )
- 【错误记录】Flutter 报错 ( Could not read script ‘xxxflutter_toolsgradleapp_plugin_loader.gradle‘ )
- 【Flutter】Flutter Gallery 官方示例简介 ( 项目简介 | 工程构建 )
- 【Flutter】Flutter Gallery 官方示例简介 ( 学习示例 | 邮件应用 | 零售应用 | 理财应用 | 旅行应用 | 新闻应用 | 自适应布局应用 )
- 【Flutter】底部导航栏实现 ( BottomNavigationBar 底部导航栏 | BottomNavigationBarItem 导航栏条目 | PageView )
- 【Flutter】Flutter 混合开发 ( 简介 | Flutter 混合开发集成步骤 | 创建 Flutter Module )
- 【Flutter】屏幕像素适配方案 ( flutter_screenutil 插件 )
- flutter系列之:如何自定义动画路由
- Flutter 绘制探索 | 绘制中的动画变换