Flutter登录后在HomeScreen展示用户信息的实现方法咨询
实现登录后在HomeScreen展示用户信息
1. 修正登录方法的逻辑顺序
原代码中存在逻辑错误:先跳转HomeScreen再解析用户数据,导致跳转后无法获取到User实例。需要调整顺序,先解析数据再跳转并传递User实例:
import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:flutter_application_1/screens/homescreen/home_screen.dart'; import 'package:http/http.dart' as http; import 'package:flutter_easyloading/flutter_easyloading.dart'; import '../models/user_model.dart'; class HttpService { static const BASE_URL = "https://091a-186-249-214-216.ngrok.io"; static const LOGIN_URL = "$BASE_URL/login"; static Future<User> login(cpf, password, context) async { final response = await http.post( Uri.parse(LOGIN_URL), headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', }, body: jsonEncode({"cpf": cpf, "senha": password}), ); if (response.statusCode == 200) { // 先解析服务器返回的用户数据 var data = jsonDecode(response.body); final user = User.fromJson(data); // 跳转时将User实例传递给HomeScreen await Navigator.push( context, MaterialPageRoute( builder: (context) => HomeScreen(user: user), ) ); return user; } else { await EasyLoading.showError( "Error Code : ${response.statusCode.toString()}"); throw Exception('Failed to load User ID'); } } }
2. 修改HomeScreen接收参数并展示信息
让HomeScreen接收必填的User参数,然后在页面布局中渲染用户的id、姓名等字段:
import 'package:flutter/material.dart'; import '../../models/user_model.dart'; class HomeScreen extends StatelessWidget { // 接收从登录页传递过来的User实例 final User user; const HomeScreen({super.key, required this.user}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('首页'), ), body: Padding( padding: const EdgeInsets.all(16.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text('用户ID: ${user.id}', style: const TextStyle(fontSize: 18)), const SizedBox(height: 8), Text('姓名: ${user.name}', style: const TextStyle(fontSize: 18)), const SizedBox(height: 8), Text('CPF: ${user.cpf}', style: const TextStyle(fontSize: 18)), const SizedBox(height: 8), Text('职位: ${user.businessRole}', style: const TextStyle(fontSize: 18)), const SizedBox(height: 8), Text('邮箱: ${user.email}', style: const TextStyle(fontSize: 18)), // 可根据需求添加其他需要展示的字段,如性别、手机号等 ], ), ), ); } }
3. 额外优化建议
- 如果需要在多个页面共享用户信息,推荐使用
Provider、Riverpod或GetX等状态管理工具,将User实例存入全局状态,避免跨页面频繁传递参数。 - 注意
acessToken的拼写(标准拼写为accessToken),若后端返回字段为AcessToken则保持一致,建议统一前后端命名规范。
内容的提问来源于stack exchange,提问作者Alef Gomes
相关产品推荐
相关产品推荐

