我在一个应用程序上使用API来获取用户信息,并在另一个选项卡中获取该特定用户的对话和消息线程,因为我知道我需要pid和tac(选项卡访问代码)作为参数,为了获取它们,它们位于另一个API(getTabAccessCode
)的响应体中,我使用Postman尝试调用,它们工作正常。
下面是user_service.dart,在postman中,在其body响应中的getTabAccessCode
函数中,我获得了User id,pid和tac(tab访问代码):
static Future<Map<String, dynamic>> fetchUserInfo(String accessToken) async {
final response = await http.get(
Uri.parse(
'https://example.app/auth/example/protocol/userinfo'),
headers: {
'Authorization': 'Bearer $accessToken',
},
);
if (response.statusCode == 200) {
return json.decode(response.body);
} else {
throw Exception(
'Error fetching user information: ${response.statusCode}');
}
}
// This function takes a global ID and an access token as parameters
static Future<Map<String, dynamic>> getTabAccessCode(
String globalId, String accessToken) async {
// This is the URL for the device registration
final tokenUrl =
'http://example.com:9080/exp/rest/DeviceRegistration';
// This is the HTTP GET request with the query parameters
final response = await http.get(
Uri.parse(
'$tokenUrl?country=United%20Kingdom&emailID=example%40gmail.com&name=Patient%20Eleven&zoneinfo=Europe%2FParis&GlobalId=$globalId&postal_code=70001&gender=Female&accesstoken=$accessToken&appname=example'),
);
// This checks if the response status code is 200, which means OK
if (response.statusCode == 200) {
// This parses the response body into a Dart object
final responseBody = jsonDecode(response.body);
// Print the entire response line
print('Response: $responseBody');
// This gets the value of "TabAccCode"
final tabAccessCode = responseBody["TabAccCode"];
// If the response includes "pid" and "doctor id", retrieve them as well
final pid = responseBody["pid"];
final doctorid = responseBody["doctorid"];
// Create a map to return all the values
final resultMap = {
"tabAccessCode": tabAccessCode,
"pid": pid,
"doctorid": doctorid,
};
// This returns the map containing all the values
return resultMap;
} else {
// This throws an exception if the response status code is not 200
throw Exception('Error getting Tab Access Info: ${response.statusCode}');
}
}
注意:getTabAccessCode
API调用的响应中tab访问代码的名称为TabAccCode
,而在会话和消息API调用的参数中则称为tac
。
有人能帮助我吗?我是一个使用API的新手,我被困在这里了。
这是conversation_page.dart,下面我试图调用函数(getTabAccessCode)
,它的响应中有pid和tac,但它说globalid和accesstoken是未定义的,因为它们已经定义了,但在user_service.dart中:
import 'dart:convert';
import 'package:efindadoc/screens/messages_page.dart';
import 'package:efindadoc/screens/user_service.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class ConversationPage extends StatefulWidget {
@override
_ConversationPageState createState() => _ConversationPageState();
}
class _ConversationPageState extends State<ConversationPage> {
List<Map<String, dynamic>> conversations = [];
String pid = '';
String tac = '';
@override
void initState() {
super.initState();
initConversations();
}
Future<void> initConversations() async {
var accessInfo = await UserService.getTabAccessCode(globalId, accessToken);
var pid = accessInfo["pid"];
var tac = accessInfo["tabAccessCode"];
await fetchConversations(pid, tac);
}
Future<void> fetchConversations(String pid, String tac) async {
final response = await http.get(Uri.parse(
'https://example.com/docs/getMessages?pid=$pid&user_type=doctor&function=conversation&tac=$tac&view_as=doctor',
));
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
if (data['success']) {
final List<dynamic> conversationData = data['data'];
conversations = conversationData
.map((conversation) => Map<String, dynamic>.from(conversation))
.toList();
}
} else {
throw Exception('Failed to load conversation data');
}
setState(() {});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Conversation Page'),
),
body: ListView.builder(
itemCount: conversations.length,
itemBuilder: (context, index) {
final conversation = conversations[index];
return ListTile(
title: Text(conversation['title']),
subtitle: Text(conversation['created']),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => MessagePage(
conversationId: conversation['id'], pid: pid, tac: tac),
),
);
},
);
},
),
);
}
}
这是messages_page.dart:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class MessagePage extends StatefulWidget {
final String conversationId;
final String pid;
final String tac;
MessagePage({required this.conversationId, required this.pid, required this.tac});
@override
_MessagePageState createState() => _MessagePageState();
}
class _MessagePageState extends State<MessagePage> {
List<Map<String, dynamic>> messages = [];
@override
void initState() {
super.initState();
fetchMessages();
}
Future<void> fetchMessages() async {
final response = await http.get(Uri.parse(
'https://example.com/doc/getMessages?user_type=doctor&function=messages&conversation_id=${widget.conversationId}&pid=$pid&tac=$tac&view_as=doctor',
));
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
if (data['success']) {
final List<dynamic> messagesData = data['data']['messages'];
messages = messagesData.map((message) => Map<String, dynamic>.from(message)).toList();
}
} else {
throw Exception('Failed to load messages data');
}
setState(() {});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Message Page'),
),
body: ListView.builder(
itemCount: messages.length,
itemBuilder: (context, index) {
final message = messages[index];
return ListTile(
title: Text(message['sender_name']),
subtitle: Text(message['message']),
// You can customize how you want to display the message data here.
// For example, you can format the sent_at date, display sender's type, etc.
);
},
),
);
}
}
1条答案
按热度按时间ecfsfe2w1#
我看了你的代码,似乎你必须加深一点你的理解,你的cnrc/ sync函数。
你的小部件是同步构建的,而你的函数是异步的。这意味着您的Widget首先构建并尝试访问尚未获取的数据。
你需要做的是使用FutureBuilder。它们是在构建自身之前等待API响应的小部件。
如果你的Widget还没有获取数据,你可以显示一个loadingIndicator或者其他什么。
希望能帮到你,我说清楚了。
期待您的更新:)