Flutter Page showing blank screen - flutter

I want to display data from api to the text and it is showing blank screen and I think I did anything required, I followed this tutrial https://docs.flutter.dev/cookbook/networking/fetch-data and still it does not work for me. I tried everything,
May you please help me.
My api call below
Future<CarDetails?> 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",
"Authorization": "Bearer $token",
}));
print("data");
print(response.data.toString());
print(response.statusCode);
if (response.statusCode == 200) {
Navigator.of(context).pushReplacement(
MaterialPageRoute(
builder: (context) => const ResultsPage(),
),
);
}
else if (response.statusCode == 500) {
// call your refresh token api here and save it in shared preference
print(response.statusCode);
await getToken();
signInData();
}
return CarDetails.fromJson(jsonDecode(response.data.toString()));
} catch (e) {
print(e);
}
My other page where I wanna show the results
class ResultsPage extends StatefulWidget {
const ResultsPage({Key? key}) : super(key: key);
#override
_ResultsPageState createState() => _ResultsPageState();
}
class _ResultsPageState extends State<ResultsPage> {
//List<CarDetails> objectList = [];
late Future<CarDetails?>? 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<CarDetails?>(
future: objectList,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data?.make??"error");
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
// By default, show a loading spinner.
return const CircularProgressIndicator();
},
),
));
}
}
My model class
class CarDetails {
String? make;
String? type;
String? model;
int? year;
String? body;
String? driveType;
String? fueType;
CarDetails(
{this.make,
this.type,
this.model,
this.year,
this.body,
this.driveType,
this.fueType});
CarDetails.fromJson(Map<String, dynamic> json) {
make = json['make'];
type = json['type'];
model = json['model'];
year = json['year'];
body = json['body'];
driveType = json['drive_type'];
fueType = json['fue_type'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['make'] = this.make;
data['type'] = this.type;
data['model'] = this.model;
data['year'] = this.year;
data['body'] = this.body;
data['drive_type'] = this.driveType;
data['fue_type'] = this.fueType;
return data;
}
}

The problem is you are replacing the widget in your navigator stack when you get success.
Future<CarDetails?> 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",
"Authorization": "Bearer $token",
}));
print("data");
print(response.data.toString());
print(response.statusCode);
if (response.statusCode == 200) {
//Get rid of this
//Navigator.of(context).pushReplacement(
// MaterialPageRoute(
// builder: (context) => const ResultsPage(),
// ),
//);
// Return your future here
return CarDetails.fromJson(jsonDecode(response.data.toString()));
}
else if (response.statusCode == 500) {
// call your refresh token api here and save it in shared preference
print(response.statusCode);
await getToken();
signInData();
}
} catch (e) {
print(e);
}

Related

fetch data flutter api

I want to get data from API and I tried the link in postman and its working here it is: [ { "Id": "14", "title": "Facebook vs instagram?", }, { "Id": "15", "title": "Facebook vs instagram?", }, { "Id": "16", "title": "Facebook vs instagram?", }, ]
but when I am trying to do a map this error appears : error catch type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List' in type cast.
Here is my code : This error appears in this file and print(recieved) print the same data as postman but the problem in map httpservice.dart:
`
class HttpService {
final String postsURL =
"";
Future<List<Post>> getPosts() async {
var request = http.MultipartRequest("POST", Uri.parse(postsURL));
request.headers.addAll(headers);
List<Post> Posts = [];
try {
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
var response = await http.Response.fromStream(streamedResponse);
final result = jsonDecode(response.body) as List;
List<Post> posts = result
.map(
(dynamic item) => Post.fromJson(item),
)
.toList();
return Posts;
}
}
`
post_model.dart :
`
class Post {
final String Id;
final String title;
Post({
required this.Id,
required this.title,
});
factory Post.fromJson(Map<String, dynamic> json) {
return Post(
Id: json['Id'] as String,
title: json['title'] as String,
);
}
}
` post.dart :
class PostsPage extends StatelessWidget {
final HttpService httpService = HttpService();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Posts"),
),
body: FutureBuilder(
future: httpService.getPosts(),
builder: (BuildContext context, AsyncSnapshot<List<Post>> snapshot) {
if (snapshot.hasData) {
List<Post> posts = snapshot.data!;
return ListView(
children: posts
.map(
(Post post) => ListTile(
title: Text(post.title),
subtitle: Text("${post.Id}"),
),
)
.toList(),
);
} else {
return Center(child: CircularProgressIndicator());
}
},
),
);
}
}
The http package gives the data as json in default. You are again trying to decode the decode the response body but the jsonDecode expects string type as parameter.
Simply, all you need to do is remove the jsonDecode
From
final result = jsonDecode(response.body) as List;
to
final result = response.body as Map<String, dynamic>;

Flutter Getting data from the api

Im having problems receiving data from the api, i a class and a function and a class to use the data but im getting null, i used the function from a class to the other in a FutureBuilder. When i get to the screen where the data is trying to be fetched im just getting the circular progress indicator and in the debug is saying Null is not a subtype of String, i tried looking for the problem but i couldn't fix it, the problem might be when im trying to use the function to the other class in the other file, any help would be much appreciated, if someone could implement his answer on the code i send it would be even more helpful.
class LoginData {
final String loginPhoneNumber;
final String loginPassword;
LoginData({
required this.loginPhoneNumber,
required this.loginPassword,
});
factory LoginData.fromJson(Map<String, dynamic> json) {
return LoginData(
loginPhoneNumber: json['phoneNumber'],
loginPassword: json['lastName']
);
}
}
// function
buildSwipeButton() {
return MenuPage(
sendData: fetchLoginData(),
);
}
Future<List<LoginData>> fetchLoginData() async {
var url = 'https://dev.api.wurk.skyver.co/api/employees';
String basicAuth = 'Basic ' +
base64Encode(
utf8.encode('${emailController.text}:${passwordController.text}'),
);
var response = await http.get(
Uri.parse(url),
headers: <String, String>{'authorization': basicAuth},
);
print(response.body);
if (response.statusCode == 200) {
print(response.statusCode);
List data1 = json.decode(utf8.decode(response.bodyBytes));
return data1.map((data) => LoginData.fromJson(data)).toList();
} else {
throw Exception('Failed to load LoginData');
}
}
// the other class that im trying to use the data from
class MenuPage extends StatefulWidget {
const MenuPage({Key? key, Future<List<LoginData>>? sendData, Future<List<LoginData>>? sendData2}) : super(key: key);
#override _MenuPageState createState() => _MenuPageState();
}
class _MenuPageState extends State<MenuPage> {
final _advancedDrawerController = AdvancedDrawerController();
void _handleMenuButtonPressed() {
_advancedDrawerController.showDrawer();
}
late LoginData data;
Future<LoginData>? sendData;
body: FutureBuilder<LoginData>(
future: sendData,
builder: (context, snapshot) {
if (snapshot.hasData) {
LoginData? data1 = snapshot.data;
data = data1!;
//print(data.loginPhoneNumber);
return afterLoginBody();
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
return Center(child: const CircularProgressIndicator());
},
),
afterLoginBody() {
return ListView.builder(
itemCount: data.loginPhoneNumber.length,
itemBuilder: (context, index){
return ListTile(
title: Text(''),
);
});
}
}
Though your question was not completely clear as what data type you are expecting from the api. I've tried to make the future builder running on your code and now you can intrepret the response you receive from the server as your needs.
import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class LoginData {
final String loginPhoneNumber;
final String loginPassword;
LoginData({
required this.loginPhoneNumber,
required this.loginPassword,
});
factory LoginData.fromJson(Map<String, dynamic> json) {
return LoginData(
loginPhoneNumber: json['phoneNumber'], loginPassword: json['lastName']);
}
}
// function
buildSwipeButton() {
return MenuPage(
sendData: fetchLoginData(),
);
}
Future<List<LoginData>> fetchLoginData() async {
var url = 'https://dev.api.wurk.skyver.co/api/employees';
String basicAuth = 'Basic ' +
base64Encode(
utf8.encode('${emailController.text}:${passwordController.text}'),
);
var response = await http.get(
Uri.parse(url),
headers: <String, String>{'authorization': basicAuth},
);
// List<Map<String,dynamic>> _dummyResponse = [
// {
// "id": "0e9ca1b9-6ef3-4e16-93e0-3b4c6c1506c3",
// "firstName": "Dibran",
// "lastName": "Krasniqi",
// "phoneNumber": "049000000",
// "idNumber": 1564654
// },
// {
// "id": "0e9ca1b9-6ef3-4e16-93e0-3b4c6c1506c5",
// "firstName": "John",
// "lastName": "Doe",
// "phoneNumber": "049123456",
// "idNumber": 65412984
// },
// {
// "id": "0e9ca1b9-6ef3-4e16-93e0-3b4c6c1506e4",
// "firstName": "Ajan",
// "lastName": "Bikliqi",
// "phoneNumber": "049105221",
// "idNumber": 456123
// }
// ];
print(response.body);
if (response.statusCode == 200) {
print(response.statusCode);
List data1 = json.decode(utf8.decode(response.bodyBytes));
return data1.map((data) => LoginData.fromJson(data)).toList();
} else {
throw Exception('Failed to load LoginData');
}
}
// the other class that im trying to use the data from
class MenuPage extends StatefulWidget {
MenuPage({
Key? key,
this.sendData,
this.sendData2,
}) : super(key: key);
Future<List<LoginData>>? sendData;
Future<List<LoginData>>? sendData2;
#override
_MenuPageState createState() => _MenuPageState();
}
class _MenuPageState extends State<MenuPage> {
// final _advancedDrawerController = AdvancedDrawerController();
// void _handleMenuButtonPressed() {
// _advancedDrawerController.showDrawer();
// }
late List<LoginData> data;
Future<LoginData>? sendData;
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder<List<LoginData>>(
future: widget.sendData!,
builder: (context, snapshot) {
if (snapshot.hasData) {
if (snapshot.data != null) {
data = snapshot.data!;
} else {
data = [];
}
//print(data.loginPhoneNumber);
return afterLoginBody();
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
return Center(child: const CircularProgressIndicator());
},
),
);
}
afterLoginBody() {
return ListView.builder(
itemCount: data.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(data[index].loginPhoneNumber),
);
});
}
}

How to map the data from a nested json object in flutter

Here I get this JSON object from the API and I need to add it to a list and return so that I can get it from the snapshot to display the data.But i get the snapshot.data as null.Please help me to solve this issue.
...
{
"Data": [
{
"product_name": "MACC Tea Master Blend 40 Bags",
"img_url": "1605262901.jpg",
"order_no": "1625809545122",
"category": [
{
"category_name": "01 Box (40 Bags)",
"order_no": "1625809545122",
"qty": "1",
"line_total": "1.79"
}
]
}
],
"ID": "200"
}
...
This is the code on how i tried so far.
...
Future<List<OrderDetails>> fetchMyOrderDetails(order_no) async {
var body = jsonEncode({"order_no": order_no});
print("order_no : " + order_no);
http.Response response = await http.post(
Uri.encodeFull(api + "get_order_details_by_orderno.php"), //url
headers: {"Accept": "application/json"},
body: body);
if (response.statusCode == 200) {
Map<String, dynamic> map = json.decode(response.body);
// var map = json.decode(response.body);
print("response.body : " + "${response.body}");
print("map : " + "${map['Data']}");
List<OrderDetails> orderDetailsList;
orderDetailsList = (json.decode(response.body)['Data'] as List)
.map((i) => OrderDetails.fromJson(i))
.toList();
return orderDetailsList;
} else {
// print("Failed to load categories");
throw Exception('Failed to load the Orders');
}
}
class OrderDetails {
final String product_name;
final String img_url;
final String order_no;
final List<Category> category;
OrderDetails({
this.product_name,
this.img_url,
this.order_no,
this.category,
});
factory OrderDetails.fromJson(Map<String, dynamic> json) {
return OrderDetails(
product_name: json['product_name'] as String,
img_url: json['img_url'] as String,
order_no: json['order_no'] as String,
category: json['category'] as List,
);
}
}
class Category {
final String category_name;
final String qty;
final String line_total;
Category({this.category_name, this.qty, this.line_total});
factory Category.fromJson(Map<String, dynamic> json) {
return Category(
category_name: json['category_name'] as String,
qty: json['qty'] as String,
line_total: json['line_total'] as String,
);
}
}
...
From the below code i try to access the data but the snapshot.data get null and the page is loading.
...
child: FutureBuilder<List<OrderDetails>>(
future: fetchMyOrderDetails(order_no),
builder: (BuildContext context, AsyncSnapshot snapshot) {
print("snapshot data : " + "${snapshot.data}");
if (snapshot.data == null) {
return Container(
child: Center(
child: CircularProgressIndicator(),
),
);
} else {
return Center(
child: Text(snapshot.data.product_name),
);
}
},
),
...
Please update OrderDetails class.
json['category'] as List is List<dynamic> , not List<Category>
factory OrderDetails.fromJson(Map<String, dynamic> json) {
return OrderDetails(
product_name: json['product_name'] as String,
img_url: json['img_url'] as String,
order_no: json['order_no'] as String,
category: (json['category'] == null)
? null
: (json['category'] as List).map(e => Category.fromJson(e)).toList(),
);
}
Future<List<OrderDetails>> fetchMyOrderDetails(order_no) async {
var body = jsonEncode({"order_no": order_no});
print("order_no : " + order_no);
http.Response response = await http.post(
Uri.encodeFull(api + "get_order_details_by_orderno.php"), //url
headers: {"Accept": "application/json"},
body: body);
if (response.statusCode == 200) {
Map<String, dynamic> map = json.decode(response.body);
print("response.body : " + "${response.body}");
print("map : " + "${map['Data']}");
List<OrderDetails> orderDetailsList;
orderDetailsList = (map['Data'] as List)
.map((i) => OrderDetails.fromJson(i))
.toList();
return orderDetailsList;
} else {
// print("Failed to load categories");
throw Exception('Failed to load the Orders');
}
}

how call method and retrive json array nested in flutter

I new used flutter. I have model but i don't understand to call method and retrive data to show in ui(interface). I using packages http post.
this my code model
import 'dart:convert';
MutasiRekResponse myModelFromJson(String str) => MutasiRekResponse.fromJson(json.decode(str));
String myModelToJson(MutasiRekResponse data) => json.encode(data.toJson());
class MutasiRekResponse {
String responseCode;
String responseMessage;
String date;
String time;
List<Content> content;
MutasiRekResponse({
this.responseCode,
this.responseMessage,
this.date,
this.time,
this.content,
});
factory MutasiRekResponse.fromJson(Map<String, dynamic> json) => MutasiRekResponse(
responseCode: json["responseCode"],
responseMessage: json["responseMessage"],
date: json["date"],
time: json["time"],
content: List<Content>.from(json["content"].map((x) => Content.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"responseCode": responseCode,
"responseMessage": responseMessage,
"date": date,
"time": time,
"content": List<dynamic>.from(content.map((x) => x.toJson())),
};
}
class Content {
String postingDate;
String valueDate;
String inputDate;
String inputTime;
String desc;
String noReff;
String amount;
String balance;
Content({
this.postingDate,
this.valueDate,
this.inputDate,
this.inputTime,
this.desc,
this.noReff,
this.amount,
this.balance,
});
factory Content.fromJson(Map<String, dynamic> json) => Content(
postingDate: json["postingDate"],
valueDate: json["valueDate"],
inputDate: json["inputDate"],
inputTime: json["inputTime"],
desc: json["desc"],
noReff: json["noReff"],
amount: json["amount"],
balance: json["balance"],
);
Map<String, dynamic> toJson() => {
"postingDate": postingDate,
"valueDate": valueDate,
"inputDate": inputDate,
"inputTime": inputTime,
"desc": desc,
"noReff": noReff,
"amount": amount,
"balance": balance,
};
}
I am using http post package, please advice code:
static Future<MutasiRekResponse> (String accNumber, String startDate, String endDate) async {
String apiURL = "URL";
var credentials = base64.encode(bytes);
var headers = {
"Content-Type": "application/json",
"Authorization": "Basic $credentials"
};
var requestBody = jsonEncode(
{'accNumber': accNumber, 'startDate': startDate, 'endDate': endDate});
http.Response apiResult =
await http.post(apiURL, body: requestBody, headers: headers);
if (apiResult.statusCode == 200) {
apiResult.body;
} else {
Exception('failed to load data');
}
final jsonObject = json.decode(apiResult.body);
final _postResult = MutasiRekResponse(jsonObject);
return _postResult;
}
how to using correct http.pos and how to call method & retrive data in ui(interface). thank you.
Future - Widget that builds itself based on the latest snapshot of interaction with a Future.
I've added a code snippet for showing a list of contents (desc and date) in a ListView.
Widget contentList() {
return FutureBuilder(
builder: (BuildContext context, AsyncSnapshot<MutasiRekResponse> dataSnapshot) {
if (dataSnapshot.connectionState == ConnectionState.none &&
dataSnapshot.hasData == null) {
return Container(child: Text('Something went wrong'));
}
return ListView.builder(
itemCount: dataSnapshot.data.content.length,
itemBuilder: (context, index) {
return Column(
children: <Widget>[
Text(dataSnapshot.data.content[index].desc);
Text(dataSnapshot.data.content[index].balance);
],
);
},
);
},
future: getMutasiDetails('your account number', '05/03/2020', '10/03/2020), // Your async function
);
}
static Future<MutasiRekResponse> getMutasiDetails(String accNumber, String startDate, String endDate) async {
String apiURL = "your api url";
var credentials = base64.encode(bytes);
var headers = {
"Content-Type": "application/json",
"Authorization": "Basic $credentials"
};
var params = Map<String, dynamic>();
params['accNumber'] = accNumber;
params['startDate'] = startDate;
params['endDate'] = endDate;
http.Response apiResult =
await http.post(apiURL, body: params, headers: headers);
if (apiResult.statusCode == 200) {
return MutasiRekResponse.fromJson(json.decode(apiResult.body));
} else {
throw Exception('failed to load data');
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Content List'),
),
body: contentList(),
);
}

how to implement json array nested in ui flutter

How can I parse json array nested object to ListView in UI using Flutter?
The API response is
{
"responseCode": "0000",
"responseMessage": "Success",
"date": "20200227",
"time": "115221",
"content": [
{
"postingDate": "20191203",
"valueDate": "20191203",
"inputDate": "20191203",
"inputTime": "214808",
"desc": "BUNGA JATUH TEMPO"
},
]
}
Can you please help me? Thanks a lot!
Just check out this example where I have parsed you JSON locally :
{
"responseCode": "0000",
"responseMessage": "Success",
"date": "20200227",
"time": "115221",
"content": [
{
"postingDate": "20191203",
"valueDate": "20191203",
"inputDate": "20191203",
"inputTime": "214808",
"desc": "BUNGA JATUH TEMPO",
"noReff": "B2100000000026",
"amount": "+20712,33",
"balance": "+6971357445,15"
},
{
"postingDate": "20191203",
"valueDate": "20191203",
"inputDate": "20191203",
"inputTime": "214809",
"desc": "BUNGA JATUH TEMPO",
"noReff": "B2100000000033",
"amount": "+13808,22",
"balance": "+6971371253,37"
}
]
}
below is the model class for the json that you provided.
// To parse this JSON data, do
//
// final myModel = myModelFromJson(jsonString);
import 'dart:convert';
MyModel myModelFromJson(String str) => MyModel.fromJson(json.decode(str));
String myModelToJson(MyModel data) => json.encode(data.toJson());
class MyModel {
String responseCode;
String responseMessage;
String date;
String time;
List<Content> content;
MyModel({
this.responseCode,
this.responseMessage,
this.date,
this.time,
this.content,
});
factory MyModel.fromJson(Map<String, dynamic> json) => MyModel(
responseCode: json["responseCode"],
responseMessage: json["responseMessage"],
date: json["date"],
time: json["time"],
content: List<Content>.from(json["content"].map((x) => Content.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"responseCode": responseCode,
"responseMessage": responseMessage,
"date": date,
"time": time,
"content": List<dynamic>.from(content.map((x) => x.toJson())),
};
}
class Content {
String postingDate;
String valueDate;
String inputDate;
String inputTime;
String desc;
String noReff;
String amount;
String balance;
Content({
this.postingDate,
this.valueDate,
this.inputDate,
this.inputTime,
this.desc,
this.noReff,
this.amount,
this.balance,
});
factory Content.fromJson(Map<String, dynamic> json) => Content(
postingDate: json["postingDate"],
valueDate: json["valueDate"],
inputDate: json["inputDate"],
inputTime: json["inputTime"],
desc: json["desc"],
noReff: json["noReff"],
amount: json["amount"],
balance: json["balance"],
);
Map<String, dynamic> toJson() => {
"postingDate": postingDate,
"valueDate": valueDate,
"inputDate": inputDate,
"inputTime": inputTime,
"desc": desc,
"noReff": noReff,
"amount": amount,
"balance": balance,
};
// remove this method from the model
static Future<MyModel> getMutasiDetails(String accNumber, String startDate, String endDate) async {
String apiURL = urlAPI";
String username = "username";
String password = "password";
var bytes = utf8.encode("$username:$password");
var credentials = base64.encode(bytes);
var headers = {
"Content-Type": "application/json",
"Authorization": "Basic $credentials"
};
var params = Map<String, dynamic>();
params['accNumber'] = accNumber;
params['startDate'] = startDate;
params['endDate'] = endDate;
http.Response apiResult =
await http.post(apiURL, body: params, headers: headers);
if (apiResult.statusCode == 200) {
return MyModel.fromJson(json.decode(apiResult.body));
} else {
throw Exception('failed to load data');
}
}
}
And below is the main file where the listview gets rendered:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:sample_project_for_api/model.dart';
import 'package:http/http.dart' as http;
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
MyModel youModel = new MyModel();
bool _isLoading = false;
#override
void initState() {
super.initState();
getMutasiDetails("0002100000291", "", "").then((value) {
youModel = value;
setState(() {
_isLoading = false;
});
});
}
Future<MyModel> getMutasiDetails(
String accNumber, String startDate, String endDate) async {
setState(() {
_isLoading = true;
});
String apiURL = "urlAPI";
String username = "username";
String password = "password";
var bytes = utf8.encode("$username:$password");
var credentials = base64.encode(bytes);
var headers = {
"Content-Type": "application/json",
"Authorization": "Basic $credentials"
};
var params = Map<String, dynamic>();
params['accNumber'] = accNumber;
params['startDate'] = startDate;
params['endDate'] = endDate;
http.Response apiResult =
await http.post(apiURL, body: params, headers: headers);
if (apiResult.statusCode == 200) {
return myModelFromJson(apiResult.body);
} else {
throw Exception('failed to load data');
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: _isLoading
? CircularProgressIndicator()
: Container(
child: ListView.builder(
itemCount: youModel.content.length,
itemBuilder: (context, i) {
return Card(
child: Column(
children: <Widget>[
Text(youModel.content[i].amount),
Text(youModel.content[i].balance),
Text(youModel.content[i].inputDate),
Text(youModel.content[i].desc),
],
),
);
})),
);
}
}
First you could take a look at this resource:
https://bezkoder.com/dart-flutter-parse-json-string-array-to-object-list/#DartFlutter_parse_complex_JSON_into_Nested_Object
It will give you a better understanding of the parsing you're trying to do.
Then take a look at this another post:
https://pusher.com/tutorials/flutter-listviews
It will give an idea of how to handle ListViews properly
List<MyModel> list=[];
var requestBody = jsonEncode({'accNumber': accNumber});
http.Response response = await http.post(apiURL, body: requestBody, headers: headers);
if (response.statusCode == 200) {
var data = json.decode(response.body);
print(data);
for (Map<String,dynamic> m in data['content']){
list.add(MyModel.fromJSON(m));
//Replace above line with your model implemtation
}
);
}