我有以下 POST 请求来登录用户:
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) {
await Navigator.push(
context, MaterialPageRoute(builder: (context) => HomeScreen()));
var data = jsonDecode(response.body);
final user = User.fromJson(data);
return user;
} else {
await EasyLoading.showError(
"Error Code : ${response.statusCode.toString()}");
}
throw Exception('Failed to load User ID');
}
}
它返回一个用户类,它的代码是:
class User {
int id;
String acessToken;
String name;
String cpf;
String gender;
String birthDate;
String businessRole;
String phoneNumber;
String email;
User({
required this.acessToken,
required this.id,
required this.name,
required this.cpf,
required this.gender,
required this.birthDate,
required this.businessRole,
required this.phoneNumber,
required this.email,
});
factory User.fromJson(Map<String, dynamic> json) {
return User(
id: json['id'],
acessToken: json['AcessToken'],
name: json['Nome'],
cpf: json['Cpf'],
gender: json['Sexo'],
birthDate: json['Data'],
businessRole: json['Cargo'],
phoneNumber: json['Numero'],
email: json['Email'],
);
}
}
JSON解码后的响应体为:
{
"AcessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjoxLCJleHAiOjE2ODc2Mzk5MjR9.NsdPaQM9w4GlAJQybKraiUf1pjcc9nM697PvU7MabkM",
"Cargo": "Engenheiro Civil",
"Cpf": "61308649304",
"Data": "2018-12-03",
"Email": "[email protected]",
"Nome": "Luigi Gabriel Silva Gomes",
"Numero": "99991974865",
"Sexo": "masculino",
"id": 1
}
如您所见,有关用户的所有数据都在 POST 请求之后提供,然后转到主页屏幕。在此屏幕上,我想显示用户信息,如:id、名称等。我应该怎么做?
一直在用chatGPT帮我解决flutter中的一些问题和解决方法。关于这个问题,我找到了一种通过添加所需参数将用户传递到配置文件屏幕的方法。有代码: 1- 传递给 HomeScreen 的正文:
class HomeScreen extends StatelessWidget {
final User user;
const HomeScreen({super.key, required this.user});
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: grey1,
body: Body(user: user),
);
}
}
2- 传递到 ProfileScreen:
class _BodyState extends State<Body> {
int _index = 0;
final List<Widget> screens = [];
@override
void initState() {
screens.addAll([
AgendaScreen(),
MissoesScreen(),
SuporteScreen(),
ProfileScreen(user: widget.user),
]);
然后我只是在个人资料屏幕中使用 user.id、user.name 等来展示用户的详细信息。
如果有人知道更好的方法,请随时帮助我。 谢谢! =)