Null response in await api - flutter

This print('response>>>>>>'); print(response); is NULL
print ("api") - this return is OK
In Api.dart
Future list(arguments) async {Dio dio = new Dio();
try {
var arg = arguments;
String refreshToken = token;
dio.options.baseUrl = serverUrl + "/test/" + arg.toString();
dio.options.responseType = ResponseType.json;
Response response = await dio.get(
"${dio.options.baseUrl}",
options: Options(
headers: {
'Authorization': "Bearer $refreshToken",
'Content-Type': "application/json;charset=UTF-8",
'Accept': "gzip"
}
)
);
print ("api");
print(response.data);
return await response.data;
} catch (e) {
print(e);
}
myclass.dart
cl
ass Page extends StatefulWidget {
#override
PageState createState() => PageState();
}
class PageState extends State<Page> {
List data;
Future<List> list() async {
Network network = new Network();
final String arguments = ModalRoute.of(context).settings.arguments as String;
print(arguments);
var response = await network.list(arguments.toString());
print('response>>>>>>');
print(response);
if (mounted){
this.setState(() {
data = response;
});
};
// _saving = false;
// print('data');
// print(data);
// return "Success!";
}
#override
void initState(){
super.initState();
// Future.delayed(Duration.zero, this.dados_propostas);
// dados_propostas();
}
#override
Widget build(BuildContext context) {
this.list();
return AlertDialog(
title: const Text('Teste'),
actions: <Widget>[
FlatButton(
onPressed: debugDumpApp,
child: Row(
children: <Widget>[
const Icon(
Icons.dvr,
size: 18.0,
),
Container(
width: 8.0,
),
const Text('DUMP'),
],
),
),
FlatButton(
onPressed: () {
Navigator.pop(context, false);
},
child: const Text('OK'),
),
],
);
}
}

Use this function:
Future<Response> get(String url, String token) async {
Response response = Response();
try {
dio.options.contentType = "application/json;charset=UTF-8";
dio.options.headers["Authorization"] = "Bearer $token";
response = await dio.get(url);
return response;
} on DioError catch (error, stacktrace) {
print("Exception occured: $error stackTrace: $stacktrace");
return error.response;
}
}

Related

Flutter: Api Request is taking too long to process

I'm trying to make an API request in my flutter application but it takes too much time to process like 15-25 seconds.When i run the same request on Postman its working fine and takes only 200 to 650 ms.I tried using diohttp and http client but result is almost same.Below is my code.
import 'package:http/http.dart' as http;
import 'package:dio_http/dio_http.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
MyApp({super.key});
Dio dioRest = Dio(
BaseOptions(
baseUrl: baseURL,
headers: {
HttpHeaders.contentTypeHeader: ContentType.json.value,
},
),
);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'MYAPP',
home: Scaffold(
appBar: AppBar(title: Text("Home page")),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
MaterialButton(
child: Text("Go to my profile"),
color: Theme.of(context).primaryColor,
onPressed: () async{
await getAllContentList();
}),
MaterialButton(
child: Text("Go to Accounts"),
color: Theme.of(context).primaryColor,
onPressed: () async{
await getAllContentListHttp();
}),
],
),
),
),
);
}
Future<List<dynamic>> getAllContentList() async {
try {
print('Api Started');
var result = await dioRest.post(baseURL+'secured/v/getAllContentList', options: Options(
headers: {
'Authorization': 'bearer $token',
'Content-Type': 'application/json',
},
));
print('API result :: $result');
if (result.statusCode == 200) {
print('API result decoded :: ${jsonDecode(result.data)}');
return jsonDecode(result.data);
}
throw DioError(requestOptions: result.requestOptions);
} on DioError catch (error) {
if (error.response!.statusCode! >= 400) {
throw AccessTokenException(message: "Token invalid or expired");
}
var businessError = BusinessError.fromJson(error.response?.data);
throw BusinessException(businessError, statusCode: error.response?.statusCode);
} catch (error) {
throw Error();
}
}
Future<List<dynamic>> getAllContentListHttp() async {
try {
print('Api Started');
Map<String, String> requestHeaders = {
'Content-Type': 'application/json',
'Authorization': 'Bearer $token',
};
String stUrl = baseURL+'protected/users/getAllActiveStreamList';
final response = await http.post(Uri.parse(baseURL+'secured/v/getAllContentList'), headers: requestHeaders);
print('API result :: $response');
if (response.statusCode == 200) {
print('API result decoded :: ${jsonDecode(response.body)}');
return jsonDecode(response.body);
}
throw AccessTokenException(message: "!!!Sorry");
} on DioError catch (error) {
if (error.response!.statusCode! >= 400) {
throw AccessTokenException(message: "Token invalid or expired");
}
var businessError = BusinessError.fromJson(error.response?.data);
throw BusinessException(businessError, statusCode: error.response?.statusCode);
} catch (error) {
throw Error();
}
}
}
Versions used :
http: ^0.13.5
dio_http: ^5.0.4

Agora Video calling local view doesn't start, warning: invalid local view

I am developing a voice/video-calling app using Flutter and Agora rtc engine (v 5.3.1). I have followed all the necessary steps for generating token and joining a channel. But, I can't see the local camera view in the UI and the logs gives me warning saying: "onWarning warn 8 msg invalid view for local video". Any leads would be big help, thanks in advance.
Logs:
W/spdlog (30579): [2023-01-04 21:02:33.375] [0] [warning] /tmp/jenkins/IRIS-SDK/rtc/cxx/src/internal/rtc_engine_event_handler.cc:43 onWarning warn 8 msg invalid view for local video
W/spdlog (30579): [2023-01-04 21:02:33.375] [0] [warning] /tmp/jenkins/IRIS-SDK/rtc/cxx/src/internal/rtc_engine_event_handler.cc:43 onWarning warn 16
msg nullptr
I/spdlog (30579): [2023-01-04 21:02:33.375] [0] [info] /tmp/jenkins/IRIS-SDK/rtc/cxx/src/internal/rtc_engine_event_handler.cc:72 onJoinChannelSuccess
channel b8667da0-8c6a-11ed-a9fb-578e8ad35bd6 uid 1
W/spdlog (30579): [2023-01-04 21:02:33.377] [0] [warning] /tmp/jenkins/IRIS-SDK/rtc/cxx/src/internal/rtc_engine_event_handler.cc:43 onWarning warn 16
msg nullptr
Call Screen Widget:
imports...
String baseUrl = 'https://...';
class CallScreen extends ConsumerStatefulWidget {
final Call call;
const CallScreen({Key? key, required this.call, }) : super(key: key);
#override
_CallScreenState createState() => _CallScreenState();
}
class _CallScreenState extends ConsumerState<CallScreen> {
int uid = 1;
List<int> _remoteUids = [];
bool isJoined = false,
switchCamera = true,
openMicrophone = true,
enableSpeakerphone = false;
late bool openCamera;
late RtcEngine _engine;
#override
void initState() {
initAgora();
openCamera = widget.call.isVideoCall;
super.initState();
}
Future<String?> _getToken() async {
String url = baseUrl + "/rtc/" + widget.call.callId + "/publisher/uid/" + uid.toString() + "/";;
String? token;
try{
var resp = await http.get(Uri.parse(url));
if(resp.statusCode == 200){
token = jsonDecode(resp.body)['rtcToken'];
return token;
}
else{
showMySnackBar(context: context, content: "Token Status ERR: "+jsonDecode(resp.body)['message']);
return null;
}
}
catch(e){
showMySnackBar(context: context, content: "Token Err: "+e.toString());
return null;
}
}
void _joinChannel() async {
String? token = await _getToken();
if(token != null){
await _engine.joinChannel(token, widget.call.callId, null, uid);
}
else{
showMySnackBar(context: context, content: 'Token is null!');
}
}
void _leaveChannel() async {
ref.read(callControllerProvider).endCall(
widget.call.callerId,
widget.call.receiverId,
context,
widget.call.isGroupChat
);
if(widget.call.isVideoCall) await _engine.stopPreview();
await _engine.leaveChannel();
}
void _switchCamera() {
_engine.switchCamera()
.then((value) {
setState(() {
switchCamera = !switchCamera;
});
})
.catchError((err) {
//print('switchCamera $err');
});
}
void _switchMicrophone() async {
// await _engine.muteLocalAudioStream(!openMicrophone);
await _engine.enableLocalAudio(!openMicrophone)
.then((value) {
setState(() {
openMicrophone = !openMicrophone;
});
})
.catchError((err) {
// print('enableLocalAudio $err');
});
}
void _switchSpeakerphone() {
_engine.setEnableSpeakerphone(!enableSpeakerphone)
.then((value) {
setState(() {
enableSpeakerphone = !enableSpeakerphone;
});
})
.catchError((err) {
//print('setEnableSpeakerphone $err');
});
}
void initAgora() async {
try{
await [Permission.microphone, Permission.camera].request();
_engine = await RtcEngine.createWithContext(RtcEngineContext(AgoraConfig.appId));
_engine.setEventHandler(
RtcEngineEventHandler(
warning: (warn) {
showMySnackBar(context: context, content: "Warn: "+warn.name);
},
error: (err) {
showMySnackBar(context: context, content: 'OnErr event: '+err.name);
},
joinChannelSuccess: (String channel, int userId, int elapsed) {
// print("local user ${connection.localUid} joined");
if(mounted){
setState(() {
isJoined = true;
uid = userId;
});
}
showMySnackBar(context: context, content: 'You ($userId) have joined the call!');
},
userJoined: (int remoteUid, int elapsed) {
//debugPrint("remote user $remoteUid joined");
if(mounted){
setState(() {
_remoteUids.add(remoteUid);
});
}
},
userOffline: (int remoteUid, UserOfflineReason reason) {
//debugPrint("remote user $remoteUid left channel");
if(mounted){
setState(() {
_remoteUids.removeWhere((element) => element == remoteUid);
});
}
},
leaveChannel: (stats) {
if(mounted){
setState(() {
isJoined = false;
if(!widget.call.isGroupChat || _remoteUids.length == 1){
_remoteUids.clear();
}
});
}
},
// onTokenPrivilegeWillExpire: (RtcConnection connection, String token) {
// debugPrint('[onTokenPrivilegeWillExpire] connection: ${connection.toJson()}, token: $token');
// },
),
);
await _engine.setChannelProfile(ChannelProfile.LiveBroadcasting);
//await _engine.setClientRole(ClientRole.Broadcaster);
await _engine.enableVideo();
if(widget.call.isVideoCall){
await _engine.startPreview();
}
else{
await _engine.muteLocalVideoStream(true);
await _engine.muteAllRemoteVideoStreams(true);
}
_joinChannel();
}
catch(e){
showMySnackBar(context: context, content: "Init Err: "+e.toString());
}
}
#override
void dispose() {
_leaveChannel();
_engine.destroy();
super.dispose();
}
// Display remote user's video
Widget _remoteVideo() {
if (_remoteUids.isNotEmpty) {
//TODO check for video on or off or if video call:
return rtc_remote_view.SurfaceView(
uid: _remoteUids[0],
channelId: widget.call.callId,
);
}
else {
return const Text(
'Please wait for others to join',
textAlign: TextAlign.center,
);
}
}
#override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async { _leaveChannel(); return true; },
child: Scaffold(
backgroundColor: Colors.white,
body: Stack(
children: [
Center(
child: _remoteVideo(),
),
Align(
alignment: Alignment.bottomRight,
child: Padding(
padding: const EdgeInsets.only(right: 18.0, bottom: 12),
child: ClipRRect(
borderRadius: const BorderRadius.all(Radius.circular(12)),
child: ColoredBox(
color: Colors.grey.shade200,
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 125, maxHeight: 175),
child: AspectRatio(
aspectRatio: 9/16,
child: Center(
child: isJoined
?
( //TODO: check for video on or off or if video call:
openCamera
? rtc_local_view.SurfaceView(
channelId: widget.call.callId,
)
: const Icon(
Icons.videocam_off_rounded,
color: Colors.black,
size: appActionsIconsSize,
)
)
: const CircularProgressIndicator(),
),
),
),
),
),
),
),
],
),
),
);
}
}
I found the issue: I was not setting the ClientRoleType correctly and that caused error in finding local view. One needs to define ClientRoleType (based on your logic) and ChannelProfileType.broadcast and everything seems to work.

Fetch data user with DIO API

I've been learning for days about him. But I still can't display it on screen. Maybe anyone can help ? please check it. i want to get some user data on my screen with Dio Package
in this dio client i try tu generalize every request in 1 .dart
Dio_Client.dart
import 'package:dio/dio.dart';
import 'package:latihan_dio/dio_interceptor.dart';
import '../../../../dio_client.dart';
import '/src/features/home/domain/user.dart';
enum RequestType { GET, POST, PUT, PATCH, DELETE }
class DioClient {
final dio = createDio();
DioClient._internal();
static final _singleton = DioClient._internal();
factory DioClient() => _singleton;
static Dio createDio() {
var dio = Dio(BaseOptions(
baseUrl: "https://reqres.in/api/users?page=2",
receiveTimeout: 20000, // 20 seconds
connectTimeout: 20000,
sendTimeout: 20000,
));
// dio.interceptors.addAll({
// AuthInterceptor(dio),
// });
// dio.interceptors.addAll({
// Logging(dio),
// });
return dio;
}
Future<Response<dynamic>> apiCall({
required String url,
required RequestType requestType,
Map<String, dynamic>? queryParameters,
Map<String, dynamic>? body,
Map<String, String>? header,
RequestOptions? requestOptions,
}) async {
late Response result;
// try {
switch (requestType) {
case RequestType.GET:
{
Options options = Options(headers: header);
result = await dio.get(url,
queryParameters: queryParameters, options: options);
break;
}
case RequestType.POST:
{
Options options = Options(headers: header);
result = await dio.post(url, data: body, options: options);
break;
}
case RequestType.DELETE:
{
Options options = Options(headers: header);
result =
await dio.delete(url, data: queryParameters, options: options);
break;
}
case RequestType.PUT:
{
Options options = Options(headers: header);
result = await dio.put(url, data: body, options: options);
break;
}
case RequestType.PATCH:
{
Options options = Options(headers: header);
result = await dio.patch(url, data: body, options: options);
break;
}
}
return result;
// if(result != null) {
// // return NetworkResponse.success(result.data);
// // } else {
// // return const NetworkResponse.error("Data is null");
// // }
// // }on DioError catch (error) {
// // return NetworkResponse.error(error.message);
// // } catch (error) {
// // return NetworkResponse.error(error.toString());
}
}
// }**
in this home screen i try to call api wit fetch user
home_screen.dart
import 'package:flutter/material.dart';
import 'package:flutter/src/foundation/key.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:latihan_dio/src/features/home/domain/user.dart';
import '../../../../dio_client.dart';
class myHomepage extends StatefulWidget {
const myHomepage({Key? key}) : super(key: key);
#override
State<myHomepage> createState() => _myHomepageState();
}
class _myHomepageState extends State<myHomepage> {
List<User> users = [];
var selectedIndex = 0;
#override
void initState() {
super.initState();
fetchData();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
Container(
child: Column(
children: [
ListView.builder(
// padding: EdgeInsets.symmetric(vertical: 16.5),
// scrollDirection: Axis.horizontal,
itemCount: users.length,
itemBuilder: (context, index) {
return Center(
child: Center(
child: Text(
'[data]${users[index]}',
style: TextStyle(
fontSize: 100,
color: Colors.red,
),
)),
);
},
),
// Text('data2'),
// Text('data3'),
// Text('data4'),
],
),
),
TextButton(
onPressed: () {},
child: Text(
'GET',
style: TextStyle(
fontSize: 100,
),
),
),
],
),
);
}
}
Future<void> fetchData() async {
var Response = await DioClient().apiCall(
url: 'https://reqres.in/api/users?page=2',
requestType: RequestType.GET,
// queryParameters: {},
);
List<dynamic> listUser = Response.data['result'];
List<User> users = listUser.map((e) => User.fromJson(e)).toList();
}
user.dart iam using freezed package for models,
// To parse this JSON data, do
//
// final user = userFromMap(jsonString);
import 'package:freezed_annotation/freezed_annotation.dart';
import 'dart:convert';
part 'user.freezed.dart';
part 'user.g.dart';
#freezed
abstract class User with _$User {
const factory User({
#JsonKey(name: 'id') int? id,
#JsonKey(name: 'email') String? email,
#JsonKey(name: 'first_name') String? firstName,
#JsonKey(name: 'last_name') String? lastName,
#JsonKey(name: 'avatar') String? avatar,
}) = _User;
factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
}
Instead of call async in initState, use FutureBuilder and you not checking the response to be success and also your get your list by calling Response.data['result'] instead of Response.data['data'] .Do like this:
Future<List<User?>> fetchData() async {
var Response = await DioClient().apiCall(
url: 'https://reqres.in/api/users?page=2',
requestType: RequestType.GET,
// queryParameters: {},
);
if (Response.statusCode == 200) {
List<dynamic> listUser = Response.data['data'];
List<User> users = listUser.map((e) => User.fromJson(e)).toList();
return users;
} else {
return [];
}
}
then use it like this:
Center(
child: FutureBuilder<List<User?>>(
future: fetchData(),
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return Text('Loading....');
default:
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
List<User?> data = snapshot.data ?? [];
return ListView.builder(
itemBuilder: (context, index) {
return Column(children: [
Text(data[index]?.firstName?? ''),
]);
},
itemCount: data.length,
);
}
}
},
),
)
try this
Future<void> fetchData() async {
var Response = await DioClient().apiCall(
url: 'https://reqres.in/api/users?page=2',
requestType: RequestType.GET,
// queryParameters: {},
);
List<dynamic> listUser = Response.data['result'];
users = listUser.map((e) => User.fromJson(e)).toList();
}
//remove reinit of userslist
Future<void> fetchData() async {
var Response = await DioClient().apiCall(
url: 'https://reqres.in/api/users?page=2',
requestType: RequestType.GET,
// queryParameters: {},
);
List<dynamic> listUser = Response.data;
// OR
List<dynamic> listUser = Response.data['data]; // if you want to acces s data inside it
List<User> users = listUser.map((e) => User.fromJson(e)).toList();
}
Try this

Server response only showing circular progress dialog and not API data Flutter

I seriously need assistance. I want to show API data on a listview, but It is not showing, only showing circular progress dialog. My api function is working well as it is printing valid json data on console. When I show and navigate to ResultsPage, It just shows circular progress dialog and not the data. Can you tell me where am I going wrong, why the data is not displaying
Your help will be appreciated.
My API function
Future<List<Autogenerated>?> signInData() async {
final prefs = await SharedPreferences.getInstance();
final String? token = prefs.getString('token');
try {
Response response = await _dio.post('$_baseUrl/api/gateway',
data: {
"ClientPackageId": "0cdd231a-d7ad-4a68-a934-d373affb5100",
"PlatformId": "ios",
"ClientUserId": "AhmedOmar",
"VinNumber": VINumber
},
options: Options(
headers: {
"Content-Type": "application/json;charset=UTF-8",
"Charset": 'utf-8',
"Authorization": "Bearer $token",
},
));
print("data is here");
print(json.encode(response.data));
print(response.statusCode);
if (response.statusCode == 200) {
print("decoded");
List<Map<String, dynamic>> map = [];
map = List<Map<String, dynamic>>.from(
jsonDecode(json.encode(response.data)));
print(map);
// return List<Autogenerated>.from(
// response.data.map((i) => Autogenerated.fromJson(i)));
// return Autogenerated.fromJson(jsonDecode(json.encode(response.data)));
} else if (response.statusCode == 500) {
// call your refresh token api here and save it in shared preference
print(response.statusCode);
await getToken();
signInData();
} else {
throw Exception('Failed to load data');
}
} catch (e) {
print(e);
}
// return null;
}
Where I want to show the list
class ResultsPage extends StatefulWidget {
const ResultsPage({Key? key}) : super(key: key);
#override
_ResultsPageState createState() => _ResultsPageState();
}
class _ResultsPageState extends State<ResultsPage> {
Future<List<Autogenerated>?>? objectList;
_APIState? api;
#override
void initState() {
super.initState();
objectList = api?.signInData();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
//centerTitle: true,
),
body: Center(
child: FutureBuilder<List<Autogenerated>?>(
future: objectList,
builder: (context, snapshot) {
if (snapshot.hasData) {
print("snapshot data:");
print(snapshot.hasData);
return Padding(
padding: const EdgeInsets.all(8.0),
child: ListView.builder(
itemCount: snapshot.data?.length,
itemBuilder: (context, index) {
var title = snapshot.data?[index].category;
// var company = snapshot.data[index]['company_name'];
// var skills = snapshot.data[index]['skills'];
// var description = snapshot.data[index]['description'];
// var positions = snapshot.data[index]['positions'];
return Card(
shape: RoundedRectangleBorder(
side: BorderSide(
color: Colors.green.shade300,
),
borderRadius: BorderRadius.circular(15.0),
),
child: ListTile(
leading: Text(title!),
title: Text(title),
subtitle: Text(
title + '\n' + title,
),
trailing: Text(title),
),
);
},
));
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
// By default, show a loading spinner.
return const CircularProgressIndicator();
},
),
));
}
}
You need to open the comment and return.
Future<List<Autogenerated>?> signInData() async {
final prefs = await SharedPreferences.getInstance();
final String? token = prefs.getString('token');
try {
Response response = await _dio.post('$_baseUrl/api/gateway',
data: {
"ClientPackageId": "0cdd231a-d7ad-4a68-a934-d373affb5100",
"PlatformId": "ios",
"ClientUserId": "AhmedOmar",
"VinNumber": VINumber
},
options: Options(
headers: {
"Content-Type": "application/json;charset=UTF-8",
"Charset": 'utf-8',
"Authorization": "Bearer $token",
},
));
print("data is here");
print(json.encode(response.data));
print(response.statusCode);
if (response.statusCode == 200) {
print("decoded");
List<Map<String, dynamic>> map = [];
map = List<Map<String, dynamic>>.from(
jsonDecode(json.encode(response.data)));
print(map);
// return List<Autogenerated>.from(
// response.data.map((i) => Autogenerated.fromJson(i)));
// return Autogenerated.fromJson(jsonDecode(json.encode(response.data)));
} else if (response.statusCode == 500) {
// call your refresh token api here and save it in shared preference
print(response.statusCode);
await getToken();
signInData();
} else {
throw Exception('Failed to load data');
}
} catch (e) {
print(e);
}
// return null;
}```

How to get value from Future with custom model in flutter

I am calling an API to get data from server and i have created a dart file (model) from (https://javiercbk.github.io/json_to_dart/)
And now i want to access that future object value.
Main.dart
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Row(
children: <Widget>[
RaisedButton(
child: Text("Click"),
onPressed: () async{
setState(() {
apiCall = true; // Set state like this
});
MemberLogin fMain = await getUser();
print('$fMain ');
},
),
],
),
),
);
}
Future<MemberLogin> getUser() async {
try {
final String _endpoint =
"https://api.com/";
Dio dio = new Dio();
Response response = await dio
.post(_endpoint, data: {"new_data": "hello"});
print("user API response - : $response ");
setState(() {
apiCall = false;
});
return MemberLogin.fromJson(response.data);
} catch (error, stacktrace) {
print("Exception occured: $error stackTrace: $stacktrace");
//return MemberLogin.withError("$error");
}
}
MemberLogin.dart
class MemberLogin {
int success;
String message;
MemberLogin({this.success, this.message});
MemberLogin.fromJson(Map<String, dynamic> json) {
success = json['success'];
message = json['message'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['success'] = this.success;
data['message'] = this.message;
return data;
}
}
Now when i print message from MemberLogin after my request MemberLogin fMain = await getUser(); .
I had debug the code and i am able to see response but i can not print or access message string.
How can i do that ?
#deepak, i simulated an api and seems to be working fine. Have you tried accessing message as fMain.message? Please see the example below,
class MyAppState extends State<MyApp> {
bool apiCall = false;
String message = '';
#override
Widget build(BuildContext context) {
return MaterialApp(home: Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(message, style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18.0),),
RaisedButton(
child: Text("Click", style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18.0),),
onPressed: () async{
apiCall = true; // Set state like this
MemberLogin fMain = await getUser();
message = fMain.message;
setState(() {
});
print('$fMain ');
},
),
],
),
),
));
}
Future<MemberLogin> getUser() async {
try {
final String _endpoint =
"http://echo.jsontest.com/key/value/message/testmessage";
Dio dio = new Dio();
Response response = await dio
.get(_endpoint);
print("user API response - : $response ");
setState(() {
apiCall = false;
});
return MemberLogin.fromJson(response.data);
} catch (error, stacktrace) {
print("Exception occured: $error stackTrace: $stacktrace");
//return MemberLogin.withError("$error");
}
}
}
class MemberLogin {
String key;
String message;
MemberLogin({this.key, this.message});
MemberLogin.fromJson(Map<String, dynamic> json) {
key = json['key'];
message = json['message'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['key'] = this.key;
data['message'] = this.message;
return data;
}
}