Fetch data user with DIO API - flutter

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

Related

convert future builder to listview builder

i want to fetch data withour using future, can someone help me to convert it ? direct using listview.builder without using future builder. and how can i post it ? i already try it for a couple days and stuck here. please explain it too
thank you
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: 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,
);
}
}
// },
),
));
}
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 [];
}
}
}
// 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 access data inside it
// List<User> users = listUser.map((e) => User.fromJson(e)).toList();
// }
as u can see here is my homepage. i make a freeze class and using dio client here.
Try this
class _myHomepageState extends State<myHomepage> {
List<User> user = [];
bool isLoading = false;
#override
void initState() {
initFunction();
super.initState();
}
void initFunction() async {
setState((){
isLoading= true;
})
user = await fetchData();
setState((){
isLoading = false;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: isLoading
? CircularProgressIndicator()
: ListView.builder(
itemBuilder: (context, index) {
return Column(children: [
Text(user[index].firstName!),
]);
},
itemCount: user.length,
);
),
));
}
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 [];
}
}
}

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;
}```

Flutter display server data / response from json

I have built a page which reads the json from recipeURL and I wish for it to display the product_name value in the json file. However for some reason my future fetchData () class isn't being read as none of the text in my if else statement is being displayed. Am I missing a simple oversight here?
EDIT: The main dart file is my main screen. This is where my navbar is created. Users are redirected to other pages when they click on the corresponding icon. Im having trouble passing BarcodePage(title:title); as parameters in my main file,26th line, can be found under Class MyAppState extends State<MyApp> {
My main dart file:
import 'package:flutter/material.dart';
import 'pages/BarcodePage.dart';
import 'pages/FoodPage.dart';
import 'pages/RecipePage.dart';
import 'pages/ShoppingPage.dart';
void main() {
runApp(MaterialApp(debugShowCheckedModeBanner: false, home: MyApp()),);
}
class MyApp extends StatefulWidget {
#override
State<StatefulWidget> createState(){
return MyAppState();
}
}
class MyAppState extends State<MyApp> {
int _selectedPage =0;
final _pageOptions= [
FoodPage(),
RecipePage(),
BarcodePage(title: ,),
ShoppingPage(),
];
#override
Widget build(BuildContext context) {
return MaterialApp(
//title: 'Best B4',
theme: ThemeData(
primarySwatch: Colors.teal,),
debugShowCheckedModeBanner: false,
home: Scaffold (
appBar: AppBar(
title:Text(
'BestB4',
style: TextStyle(
fontFamily: 'PacificoRegular',
fontSize: 30,
),
),
backgroundColor: Colors.teal,
elevation: 20,
actions: [
IconButton(
icon: Icon(Icons.qr_code_2_rounded),
tooltip: 'Add item',
onPressed:(){
Navigator.push(
context,
MaterialPageRoute(builder: (context) => BarcodePage()));
},
)
],
//ONPRESSED MENU OPEN
),
body:_pageOptions[_selectedPage],
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
backgroundColor: Colors.teal,
selectedItemColor: Colors.white,
unselectedItemColor: Colors.white70,
iconSize: 40,
selectedFontSize: 15,
unselectedFontSize: 15,
currentIndex:_selectedPage,
onTap: (int index) {
setState(() {
_selectedPage = index;
});
},
items: [
BottomNavigationBarItem(
icon:Icon(Icons.restaurant_rounded),
label: 'Food',
), //, title:Text('Food')
BottomNavigationBarItem(
icon:Icon(Icons.menu_book_rounded),
label:'Recipes',
),//, title:Text('Recipes')
BottomNavigationBarItem(
icon:Icon(Icons.add_outlined),
label:'Add',
),//, title:Text('Add')
BottomNavigationBarItem(
icon:Icon(Icons.shopping_cart_rounded),
label:'Shopping',
),//,title:Text('Shopping')
],
),
),
);
}
}
My BarcodePage dart file:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as p;
import 'package:flutter/services.dart';
import 'package:barcode_scan2/barcode_scan2.dart';
import 'package:http/http.dart';
class BarcodePage extends StatefulWidget{
const BarcodePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
_BarcodePageState createState() => _BarcodePageState();
}
var futuredata = {};
class _BarcodePageState extends State<BarcodePage> {
int counter=0;
String result= "";
Future _scanBarcode() async{
try{
ScanResult scanResult = await BarcodeScanner.scan();
String barcodeResult = scanResult.rawContent;
setState(() {
result = barcodeResult;
});
} on PlatformException catch (ex) {
if (ex.code == BarcodeScanner.cameraAccessDenied) {
setState((){
result = "CAMERA PERMISSION WAS DENIED. \n EDIT THIS IN YOUR SETTINGS";
});
}else {
setState(() {
result = "404 ERROR UNKNOWN $ex";
});
}
} on FormatException {
setState(() {
result = "SCAN AN ITEM";
});
} catch (ex){
setState(() {
result = "404 ERROR UNKNOWN $ex";
});
}
}
#override
void initState() {}
fetchmydata() async {
var request = p.Request(
'GET',
Uri.parse(
'https://world.openfoodfacts.org/api/v0/product/5060391623139.json'));
StreamedResponse response = await request.send();
if (response.statusCode == 200) {
// print(await response.stream.bytesToString());
var data = await response.stream.bytesToString();
futuredata = json.decode(data);
} else {
print(response.reasonPhrase);
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.teal,
title:Text('Add an item',
style: TextStyle(
fontFamily: 'Fredoka',
fontSize: 25,
),
),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
FutureBuilder(
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting)
return Center(
child: Container(
child: CircularProgressIndicator(),
height: 50,
width: 50,
),
);
else if (snapshot.connectionState == ConnectionState.done)
return ListTile(
title: Text(futuredata["product"]["product_name"].toString()),
subtitle: Text("France:" +
futuredata["product"]["product_name_en"].toString()),
);
else {
return Container(
child: CircularProgressIndicator(),
height: 50,
width: 50,
);
}
},
future: fetchmydata(),
)
],
),
floatingActionButton: FloatingActionButton.extended(
backgroundColor: Color.fromRGBO(51, 171, 160, 100),
icon: Icon(Icons.camera_alt),
label: Text("Scan"),
onPressed: _scanBarcode,
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
);
}
}
The Json file looks like this:
JSON LINK: https://world.openfoodfacts.org/api/v0/product/5060391623139.json
You can read your json like this
var futuredata = {};
var productname= futuredata["product"]["product_name"]
Your fetch method like this
fetchmydata() async {
var request = p.Request(
'GET',
Uri.parse(
'https://world.openfoodfacts.org/api/v0/product/5060391623139.json'));
StreamedResponse response = await request.send();
if (response.statusCode == 200) {
// print(await response.stream.bytesToString());
var data = await response.stream.bytesToString();
futuredata = json.decode(data);
} else {
print(response.reasonPhrase);
}
}
With model Class
SampleModel? Mymodel = null;
fetchmydata() async {
var request = p.Request(
'GET',
Uri.parse(
'https://world.openfoodfacts.org/api/v0/product/5060391623139.json'));
StreamedResponse response = await request.send();
if (response.statusCode == 200) {
// print(await response.stream.bytesToString());
var data = await response.stream.bytesToString();
futuredata = json.decode(data);
Mymodel = SampleModel.fromJson(futuredata);
} else {
print(response.reasonPhrase);
}
}
in the method we first read data from json as string or text
then we decode the string type or text from server to map type
SampleCode Dartpad live code check
import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart';
import 'package:http/http.dart' as p;
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
var futuredata = {};
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
#override
void initState() {}
fetchmydata() async {
var request = p.Request(
'GET',
Uri.parse(
'https://world.openfoodfacts.org/api/v0/product/5060391623139.json'));
StreamedResponse response = await request.send();
if (response.statusCode == 200) {
// print(await response.stream.bytesToString());
var data = await response.stream.bytesToString();
futuredata = json.decode(data);
} else {
print(response.reasonPhrase);
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
FutureBuilder(
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting)
return Center(
child: Container(
child: CircularProgressIndicator(),
height: 50,
width: 50,
),
);
else if (snapshot.connectionState == ConnectionState.done)
return ListTile(
title: Text(futuredata["product"]["product_name"].toString()),
subtitle: Text("France:" +
futuredata["product"]["product_name_en"].toString()),
);
else {
return Container(
child: CircularProgressIndicator(),
height: 50,
width: 50,
);
}
},
future: fetchmydata(),
)
],
),
);
}
}
Sample ModelClass
///
/// Code generated by jsonToDartModel https://ashamp.github.io/jsonToDartModel/
///
class SampleModelProduct {
/*
{
"_id": "5060391623139",
"_keywords": [
"peanut"
],
"product_name": "Peanut butter",
"product_name_en": "Peanut butter",
"product_name_fr": "Peanut butter"
}
*/
String? Id;
List<String?>? Keywords;
String? productName;
String? productNameEn;
String? productNameFr;
SampleModelProduct({
this.Id,
this.Keywords,
this.productName,
this.productNameEn,
this.productNameFr,
});
SampleModelProduct.fromJson(Map<String, dynamic> json) {
Id = json['_id']?.toString();
if (json['_keywords'] != null) {
final v = json['_keywords'];
final arr0 = <String>[];
v.forEach((v) {
arr0.add(v.toString());
});
Keywords = arr0;
}
productName = json['product_name']?.toString();
productNameEn = json['product_name_en']?.toString();
productNameFr = json['product_name_fr']?.toString();
}
Map<String, dynamic> toJson() {
final data = <String, dynamic>{};
data['_id'] = Id;
if (Keywords != null) {
final v = Keywords;
final arr0 = [];
v!.forEach((v) {
arr0.add(v);
});
data['_keywords'] = arr0;
}
data['product_name'] = productName;
data['product_name_en'] = productNameEn;
data['product_name_fr'] = productNameFr;
return data;
}
}
class SampleModel {
/*
{
"code": "5060391623139",
"product": {
"_id": "5060391623139",
"_keywords": [
"peanut"
],
"product_name": "Peanut butter",
"product_name_en": "Peanut butter",
"product_name_fr": "Peanut butter"
},
"status": 1,
"status_verbose": "product found"
}
*/
String? code;
SampleModelProduct? product;
int? status;
String? statusVerbose;
SampleModel({
this.code,
this.product,
this.status,
this.statusVerbose,
});
SampleModel.fromJson(Map<String, dynamic> json) {
code = json['code']?.toString();
product = (json['product'] != null)
? SampleModelProduct.fromJson(json['product'])
: null;
status = json['status']?.toInt();
statusVerbose = json['status_verbose']?.toString();
}
Map<String, dynamic> toJson() {
final data = <String, dynamic>{};
data['code'] = code;
if (product != null) {
data['product'] = product!.toJson();
}
data['status'] = status;
data['status_verbose'] = statusVerbose;
return data;
}
}
try creating a .g.dart file using flutter packages pub run build_runner build. flutter automatically will create your binding class factory. once you have the binding classes created flutter will automatically code your binding class, including nested classes. I personally think automation is the way to handle all interactions with json from the server. The reason you want to use the future .g.dart code generator is to reduce the possibility of error and incorrect type casting.
file.dart
factory ProductView.fromJson(Map<String, dynamic> json) =>
_$ProductFromJson(json);
Map<String, dynamic> toJson() => _$ProductViewToJson(this);
file.g.dart
ProductView _$ProductViewFromJson(Map<String, dynamic> json) {
return
ProductView(
json['field1'] as int,
json['field2'] as String,
json['field3'] == null
? null
: DateTime.parse(json['field3'] as String),
);
}
Map<String, dynamic> _$ProjectViewToJson(ProductView instance) =>
<String, dynamic>{
'field1': instance.field1,
'field2': instance.field2,
'field3': instance.field3?.toIso8601String(),
};
decoding the json
var client = http.Client();
Map<String, String> headers = new HashMap();
headers['Accept'] = 'application/json';
headers['Content-Type'] = 'application/json';
headers['Authorization'] = 'Bearer $token';
var response = await client.get(url, headers: headers).timeout(_TIMEOUT);
var parsed = json.decode(response.body);
var view = ProductView.fromJson(parsed);

can't understand http request problem though it works fine last 7 days ago in flutter

I made a http request using dio. and it displayed as listview in flutter app. it works fine in my project properly. but since last 7 days it shows problem. i can't understand what type o problem it has and what is the solution?
If it have backend error then it will shows 500. but in logcat, lots of line runnig but not exectly problem shows. but some problem shows in emulator screen.
This is api request
Future<List<ListAlbum>> listData() async {
final token = ""; //token data
String url =
'https://portal-api.jomakhata.com/api/getRequestedLeaveList?token=${token}';
Dio dio = new Dio();
dio.options.headers['Content-Type'] = 'application/json';
final body = {'limit': 10, 'orderBy': 'idLeaveApplication', 'orderType': 'DESC'};
final response = await dio.post(url, data: body);
if (response.statusCode == 200) {
print(response.statusCode);
print(response.data);
return response.data["data"]["data"]
.map<ListAlbum>((json) => ListAlbum.fromJson(json))
.toList();
} else {
throw Exception('Failed!');
}
}
Full Code
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:dio/dio.dart';
import 'package:shared_preferences/shared_preferences.dart';
class LeaveList extends StatefulWidget {
const LeaveList({Key? key}) : super(key: key);
#override
_LeaveListState createState() => _LeaveListState();
}
class _LeaveListState extends State<LeaveList> {
late SharedPreferences sharedPreferences;
late Future<List<ListAlbum>> futureAlbum;
#override
void initState() {
super.initState();
futureAlbum = listData();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: FutureBuilder<List<ListAlbum>>(
future: futureAlbum,
builder: (context, snapshot) {
if (snapshot.hasData) {
print(snapshot.data);
return ListView.builder(
itemCount: snapshot.data!.length,
itemBuilder: (context, index) {
final ListAlbum item = snapshot.data![index];
return ListTile(
leading: Text(item.totalDay!.toString()),
title: Text(item.fullName!),
subtitle: Text(item.localHr!),
trailing: Text(item.submissionDate!),
onTap: () {
// Navigator.push(
// context,
// MaterialPageRoute(
// builder: (BuildContext context) =>
// DetailsListOrganizationData()),
// );
},
);
},
);
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
return const CircularProgressIndicator();
},
),
));
}
}
class ListAlbum {
final int? idLeaveApplication;
final int? idEmployee;
final String? customID;
final String? status;
final String? lineSupervisor;
final String? fullName;
final int? totalDay;
final String? submissionDate;
final String? reportingSupervisor;
final String? localHr;
ListAlbum({
this.idLeaveApplication,
this.idEmployee,
this.customID,
this.status,
this.lineSupervisor,
this.fullName,
this.totalDay,
this.submissionDate,
this.reportingSupervisor,
this.localHr,
});
factory ListAlbum.fromJson(Map<String, dynamic> json) {
return ListAlbum(
idLeaveApplication: json['idLeaveApplication'],
idEmployee: json['idEmployee'],
customID: json['customID'],
status: json['status'],
lineSupervisor: json['lineSupervisor'],
fullName: json['fullName'],
totalDay: json['totalDay'],
submissionDate: json['submissionDate'],
reportingSupervisor: json['reportingSupervisor'],
localHr: json['localHr'],
);
}
}
Future<List<ListAlbum>> listData() async {
// SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
// final token = sharedPreferences.getString("token");
final token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjI4OTksImlzcyI6Imh0dHBzOi8vcG9ydGFsLWFwaS5qb21ha2hhdGEuY29tL2FwaS9hdXRoL2xvZ2luIiwiaWF0IjoxNjMxMjUxNjYwLCJleHAiOjE2MzEzMzgwNjAsIm5iZiI6MTYzMTI1MTY2MCwianRpIjoiNlFEUTZCYnBMT0JhdUJoaSJ9.jAY_2nYxjgsIvXZY5vn0vAr_pwF6UBYbSGZ8wqD0YPQ';
String url =
'https://portal-api.jomakhata.com/api/getRequestedLeaveList?token=${token}';
Dio dio = new Dio();
dio.options.headers['Content-Type'] = 'application/json';
final body = {'limit': 10, 'orderBy': 'idLeaveApplication', 'orderType': 'DESC'};
final response = await dio.post(url, data: body);
if (response.statusCode == 200) {
print(response.statusCode);
print(response.data);
return response.data["data"]["data"]
.map<ListAlbum>((json) => ListAlbum.fromJson(json))
.toList();
} else {
throw Exception('Failed!');
}
}
Error Emulator screen
so what is the solution?

Null response in await api

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;
}
}