当前位置: 首页 > news >正文

Flutter---个人信息(3)---实现修改性别

效果图:点击性别一行,可以更改性别信息

实现步骤

1.添加回调函数

  final Function(String) onGenderChanged;//1,添加回调函数

2.添加必须传入的性别回调函数

const PersonInformationPage({super.key,required this.onNameChanged,required this.onGenderChanged});//2.添加必须传入的性别回调函数

3.在性别一行设置点击事件的提示框

            onTap: () {//3.设置修改性别的提示框changeGenderDialog();},

4.定义修改性别的弹窗

//4.定义修改性别的弹窗//========================修改性别的弹窗========================================//void changeGenderDialog() {showDialog(context: context,builder: (context) {return Dialog(backgroundColor: Colors.white, //背景颜色shape: RoundedRectangleBorder( //形状配置borderRadius: BorderRadius.circular(26),),child: Container(width: 250, // 自定义宽度padding: EdgeInsets.all(16), // 内边距child: Column(mainAxisSize: MainAxisSize.min,children: [// 男性选项ListTile(dense: true, //紧凑模式title: Text("男", style: TextStyle(fontSize: 16, color: Color(0xFF3D3D3D))),trailing: _selectedGender == "男" //只有选中“男”,才显示男性行尾部图标(三元运算符)? Image.asset("assets/images/cherry.png", width: 24, height: 24): null,//点击事件onTap: () {Navigator.pop(context);//关闭对话框setState(() {_selectedGender = "男"; //更新性别变量值});widget.onGenderChanged("男");// 调用回调函数,传值回主页},),// 女性选项ListTile(dense: true,//紧凑模式title: Text("女", style: TextStyle(fontSize: 16, color: Color(0xFF3D3D3D))),trailing: _selectedGender == "女" //只有选中“女”,才显示女性行尾部图标? Image.asset("assets/images/cherry.png", width: 24, height: 24): null,onTap: () {Navigator.pop(context);setState(() {_selectedGender = "女";  //更新性别变量值});widget.onGenderChanged("女");// 调用回调函数,传值回主页},),],),),);},);}

5.回到主页面(home_page),获取回调函数的值,并更新UI

                onGenderChanged: (newGender){setState(() {_homeGender = newGender; //5.接收子页面传过来的新性别,引发UI重建});},

代码实例

home_page.dart

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:my_flutter/person_information_page.dart';class HomePage extends StatefulWidget {const HomePage({super.key});@overrideState<StatefulWidget> createState() => _HomePageState();
}class _HomePageState extends State<HomePage> {var _homeGender = "男"; //性别var _homeName = "西西没烦恼"; //昵称var _homeBirthday = "2000-01-01"; // 出生年月var _homeHeight = "183"; // 身高// =======================计算具体年龄的方法=================================int get _age {try {//将字符串格式的生日(如 "2000-01-01")转换为 DateTime对象final birthDate = DateTime.parse(_homeBirthday);final now = DateTime.now(); //获取当前日期时间int age = now.year - birthDate.year; //计算基础年龄(虚岁)if (now.month < birthDate.month || (now.month == birthDate.month && now.day < birthDate.day)) { //判断是否已过生日(实岁)age--;}return age;} catch (e) {return 23; // 默认年龄}}//构建UI@overrideWidget build(BuildContext context) {return Scaffold(body: Container(height: double.infinity,padding: const EdgeInsets.all(16),// 主页背景颜色decoration: const BoxDecoration(gradient: LinearGradient(//渐变begin: Alignment.topCenter,end: Alignment.centerRight,colors: [Color(0xFF62F4F4),Color(0xFFF6F7F9),],),),child: SingleChildScrollView( //可滚动的页面physics: const ClampingScrollPhysics(),child: Column(crossAxisAlignment: CrossAxisAlignment.start,children: [// 个人信息buildUserInfo(),const SizedBox(height: 25),],),),),);}//=======================个人信息的UI=====================================Widget buildUserInfo() {return Column(mainAxisAlignment: MainAxisAlignment.center,children: [const SizedBox(height: 96),// 头像:讲图片裁剪成圆形ClipOval(child: Image.asset("assets/images/apple.png",width: 90,height: 90,fit: BoxFit.cover,),),const SizedBox(height: 8),// 昵称Row(mainAxisAlignment: MainAxisAlignment.center,children: [GestureDetector(onTap: () {  //点击跳转个人信息详情页面//8.获取回调过来的昵称Navigator.push(context, MaterialPageRoute(builder: (context)=> PersonInformationPage(onNameChanged: (newName) {setState(() {_homeName = newName;//更新首页名字变量,引发UI重建});},onGenderChanged: (newGender){setState(() {_homeGender = newGender; //5.接收子页面传过来的新性别,引发UI重建});},)));},child: Row(mainAxisAlignment: MainAxisAlignment.center,children: [Text(_homeName, // 名字style: TextStyle(color: const Color(0xFF3D3D3D),fontWeight: FontWeight.bold,fontSize: 24,),),const SizedBox(width: 10),Image.asset("assets/images/cherry.png",width: 20,height: 20,),],),),],),const SizedBox(height: 8),// 个人资料Row(mainAxisAlignment: MainAxisAlignment.center,children: [Text(_homeGender, //性别style: TextStyle(color: const Color(0xFF3D3D3D), fontSize: 16),),// 竖线分隔符Container(width: 1,height: 16,margin: const EdgeInsets.symmetric(horizontal: 12),color: const Color(0xFFD8D8D8),),Text("${_age}岁", // 年龄style: TextStyle(color: const Color(0xFF3D3D3D), fontSize: 16),),// 竖线分隔符Container(width: 1,height: 16,margin: const EdgeInsets.symmetric(horizontal: 12),color: const Color(0xFFD8D8D8),),Text(_homeHeight,//身高style: TextStyle(color: const Color(0xFF3D3D3D), fontSize: 16),),Text("cm",style: TextStyle(color: const Color(0xFF3D3D3D), fontSize: 16),),],),],);}}

personal_information_page.dart

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';class PersonInformationPage extends StatefulWidget {const PersonInformationPage({super.key,required this.onNameChanged,required this.onGenderChanged});//2.添加必须传入的性别回调函数final Function(String) onNameChanged;final Function(String) onGenderChanged;//1,添加回调函数@overrideState<StatefulWidget> createState() => _PersonInformationPageState();
}class _PersonInformationPageState extends State<PersonInformationPage> {var _selectedGender = "男";//性别var _name = "西西没烦恼"; //昵称var _birthday = "2025-10-01";//初始日期var _height = "183"; //身高final TextEditingController _nameController = TextEditingController();@overridevoid initState(){super.initState();_nameController.text = _name;}@overridevoid dispose(){_nameController.dispose();super.dispose();}// 构建UI@overrideWidget build(BuildContext context) {return Scaffold(body: Container(height: double.infinity,padding: const EdgeInsets.all(16),// 主页背景颜色decoration: const BoxDecoration(gradient: LinearGradient( //颜色渐变begin: Alignment.topCenter,end: Alignment.centerRight,colors: [Color(0xFF62F4F4),Color(0xFFF7F7F9),],),),child: SingleChildScrollView( //可滚动的页面child: Column(mainAxisAlignment: MainAxisAlignment.start,children: [const SizedBox(height: 96),// 头像:裁剪成圆形ClipOval(child: Image.asset("assets/images/apple.png",width: 90,height: 90,fit: BoxFit.cover,),),const SizedBox(height: 8),Row(mainAxisAlignment: MainAxisAlignment.center,children: [Text("点击更换头像",style: TextStyle(color: const Color(0xFF3D3D3D),fontWeight: FontWeight.bold,fontSize: 24,),),const SizedBox(width: 10),],),const SizedBox(height: 8),Text("点击可更换个人信息",style: TextStyle(color: const Color(0xFF3D3D3D).withOpacity(0.6),fontSize: 12,),),const SizedBox(height: 38),// 个人信息列表buildListInformation(),],),),),);}//===========================个人信息列表=======================================//Widget buildListInformation() {return Padding(padding: const EdgeInsets.only(top: 10),child: Container(padding: const EdgeInsets.symmetric(horizontal: 30, vertical: 31),decoration: BoxDecoration(color: Colors.white,borderRadius: BorderRadius.circular(30),),child: Column(mainAxisAlignment: MainAxisAlignment.center,children: [// 昵称GestureDetector(onTap: () {ChangeNameDialog();},child: Row(children: [Text("昵称",style: TextStyle(fontSize: 16, color: Color(0xFF3D3D3D)),),const Spacer(),Text(_name,style: TextStyle(color: Color(0xFF3D3D3D).withOpacity(0.6),fontSize: 14,),),const SizedBox(width: 6),Image.asset("assets/images/cherry.png",width: 30,height: 30,),],),),const SizedBox(height: 28),// 性别GestureDetector(onTap: () {//3.设置修改性别的提示框changeGenderDialog();},child: Row(children: [Text("性别",style: TextStyle(fontSize: 16, color: Color(0xFF3D3D3D)),),const Spacer(),Text(_selectedGender, // 显示当前选中性别style: TextStyle(color: Color(0xFF3D3D3D).withOpacity(0.6),fontSize: 14,),),const SizedBox(width: 6),Image.asset("assets/images/cherry.png",width: 30,height: 30,),],),),const SizedBox(height: 28),// 生日GestureDetector(onTap: () {},child: Row(children: [Text("生日",style: TextStyle(fontSize: 16, color: Color(0xFF3D3D3D)),),const Spacer(),Text(_birthday,style: TextStyle(color: Color(0xFF3D3D3D).withOpacity(0.6),fontSize: 14,),),const SizedBox(width: 6),Image.asset("assets/images/cherry.png",width: 30,height: 30,),],),),const SizedBox(height: 28),// 身高GestureDetector(onTap: () {},child: Row(children: [Text("身高",style: TextStyle(fontSize: 16, color: Color(0xFF3D3D3D)),),const Spacer(),Text(_height,style: TextStyle(color: Color(0xFF3D3D3D).withOpacity(0.6),fontSize: 14,),),Text("cm",style: TextStyle(color: Color(0xFF3D3D3D).withOpacity(0.6),fontSize: 14,),),const SizedBox(width: 6),Image.asset("assets/images/cherry.png",width: 30,height: 30,),],),),],),),);}//========================修改名字的弹窗========================================//void ChangeNameDialog() {_nameController.text = _name; //设置当前名字到输入框showDialog(context: context,builder: (builder) {return Dialog(shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(26),),child: Container(width: 263,padding: EdgeInsets.only(top: 20,bottom: 29,left: 34,right: 34),decoration: BoxDecoration(color: Colors.white, //背景颜色borderRadius: BorderRadius.circular(26),),child: Column(mainAxisSize: MainAxisSize.min,crossAxisAlignment: CrossAxisAlignment.start,children: [Row(mainAxisAlignment: MainAxisAlignment.center,children: [Text("修改昵称",style: const TextStyle(color: Colors.black,fontSize: 22,fontWeight: FontWeight.bold,),),],),SizedBox(height: 16),Container(padding: EdgeInsets.symmetric(horizontal: 12),decoration: BoxDecoration(color: Color(0xFFD8D8D8),//输入框颜色borderRadius: BorderRadius.circular(7),),child: TextField( //创建文本输入框组件controller: _nameController, //控制器:用于获取或者设置输入框文本内容style: TextStyle(color: Colors.white),decoration: InputDecoration(//hintText: "请输入",//提示性文字hintStyle: TextStyle(color: Colors.white54),border: InputBorder.none,),),),SizedBox(height: 20),Row(children: [//取消按钮Expanded(child: Container(height: 44, // 固定高度child: TextButton(onPressed: () => Navigator.pop(context),style: TextButton.styleFrom(backgroundColor: Color(0xFFD8D8D8),shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(26),),),child: Text("取消",style: TextStyle(color: Color(0xFF3D3D3D), fontSize: 16),),),),),SizedBox(width: 50),//确定按钮Expanded(child: Container(height: 44, // 固定高度child: TextButton(onPressed: () {//确定按钮具体的实现逻辑if(_nameController.text.trim().isNotEmpty){ //检查输入框内容是否非空String newName = _nameController.text.trim(); //获取输入框的文本内容setState(() {_name = newName; //当前页面状态,触发界面重绘});widget.onNameChanged(newName); //调用回调函数通知首页(home_page)Navigator.pop(context);//关闭对话框}},style: TextButton.styleFrom(backgroundColor: Color(0xff1F8FFF),shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(26),),),child: Text("确定",style: TextStyle(color: Colors.white, fontSize: 16),),),),),],)],),),);},).then((value) { //处理异步操作完成后的回调if(value != null && mounted) { //检查返回的结果不为空 && 检查当前组件是否还在挂载状态(避免在组件销毁后更新状态)Navigator.pop(context, value); //返回上一页并传递数据}});}//4.定义修改性别的弹窗//========================修改性别的弹窗========================================//void changeGenderDialog() {showDialog(context: context,builder: (context) {return Dialog(backgroundColor: Colors.white, //背景颜色shape: RoundedRectangleBorder( //形状配置borderRadius: BorderRadius.circular(26),),child: Container(width: 250, // 自定义宽度padding: EdgeInsets.all(16), // 内边距child: Column(mainAxisSize: MainAxisSize.min,children: [// 男性选项ListTile(dense: true, //紧凑模式title: Text("男", style: TextStyle(fontSize: 16, color: Color(0xFF3D3D3D))),trailing: _selectedGender == "男" //只有选中“男”,才显示男性行尾部图标(三元运算符)? Image.asset("assets/images/cherry.png", width: 24, height: 24): null,//点击事件onTap: () {Navigator.pop(context);//关闭对话框setState(() {_selectedGender = "男"; //更新性别变量值});widget.onGenderChanged("男");// 调用回调函数,传值回主页},),// 女性选项ListTile(dense: true,//紧凑模式title: Text("女", style: TextStyle(fontSize: 16, color: Color(0xFF3D3D3D))),trailing: _selectedGender == "女" //只有选中“女”,才显示女性行尾部图标? Image.asset("assets/images/cherry.png", width: 24, height: 24): null,onTap: () {Navigator.pop(context);setState(() {_selectedGender = "女";  //更新性别变量值});widget.onGenderChanged("女");// 调用回调函数,传值回主页},),],),),);},);}}

http://www.dtcms.com/a/549111.html

相关文章:

  • 做个网站需要什么制作软件的网站
  • 河北手机响应式网站建设设计企业门户网站管理制度
  • Docker简介与优豆云环境搭建
  • 后端面试实战:手写 Java 线程池核心逻辑,解释核心参数的作用
  • 免费做数学题的网站大连装修公司排名榜
  • Spring Al学习5 :聊天模型 API
  • 分布式锁深度解析:从架构本质到生产实践
  • 浏览器就是画板!PaintBoard让创意灵感不再受设备限制
  • 网站建设要学哪种计算机语言小学生一分钟新闻播报
  • FT8370A/B/C/CD/CP高性能次边同步整流芯片典型电路及管脚定义
  • MySQL(五) - 数据连接查询和子查询操作
  • STM32——WWDG
  • STM32-音频播放
  • 前端学习:选择器的类别
  • 运输网站建设wordpress 不同page
  • Qt的Debug版本和Release版本有什么区别?
  • Docker使用【容器】
  • 行业电子商务网站建设房地产网站开发公司电话
  • LangChain 提示模板之少样本示例(二)
  • Product Hunt 每日热榜 | 2025-10-30
  • Spring MVC核心概念
  • 鸿蒙HDF框架源码分析
  • Springboot旅游管理系统8cx8xy5m(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
  • ppt免费制作网站如何建设网站山东济南兴田德润官网
  • 如何获取网站根目录链接诸城做网站的
  • GPT-0: Attention+Transformer+可视化
  • 告别“人眼扫描”:EasyGBS智能搜索功能助力重塑海量视频监控管理效率
  • 【ubuntu】ubuntu系统如何快速删除当前用户的配置
  • dz地方门户网站制作南昌seo招聘信息
  • 灵犀科技网站开发湖南网站建设的公司排名