I created API for my Flutter app.
Here I printed json decoded response.body:
{data: [{id: 7, provider_id: 1, uid: 2194250, name: , account_id: 1950002701, owner_id: 1, advisor_id: 2111785, currency: €, account_type: Investment, status: Confirmed, is_active: true, opened_at: null, created_at: 2023-11-27T14:06:59.610+01:00, updated_at: 2023-11-27T14:06:59.610+01:00}]}
Here is how I am handling data from API:
if (response.statusCode == 200) {
var jsonResponse = json.decode(response.body);
print(jsonResponse);
AccountController accountController = Get.find<AccountController>();
accountController.updateAccountData(jsonResponse);
} else {
Map<String, dynamic> jsonResponse = json.decode(response.body);
print(jsonResponse);
}
Here is my AccountController.dart file
import 'package:get/get.dart';
class AccountController extends GetxController {
RxList<Map<String, dynamic>> accountData = <Map<String, dynamic>>[].obs;
void updateAccountData(Map<String, dynamic> data) {
accountData.assignAll([data]);
}
}
I also put Get.put(AccountController()); into my main.dart file.
This is how I am calling accountController in different widget
AccountController? accountController;
String? currency;
String? accountType;
@override
void initState() {
super.initState();
accountController = Get.find<AccountController>();
}
My question is, how can I loop trough this array and render items? Maybe I did everything wrong, I am new to flutter and hope I will learn something.
Okay, First of all, ignore all comments that says change your state management, since you are new to flutter, it is good for you because it will simplify things.
Now:
Data Modeling
instead of writing something like this:or this:
It will be better to convert the JSON to a Datatype object, (Class).
the easiest way to do that is to use third-party tools such as : https://app.quicktype.io/
copy your response and paste it into the website, then select Dart as a programming language. the website will generate a class for you like this:
Parsing JSON to Data Model
and in your controller:
And Please Note: this way is not organized, but in start it's good for you to make your first API call, read more about MVC, and do not start with complex level of coding.