I wanted to make connection with my WordPress with API, I successfully made the connection and fetched JSON, here is the connection code
// ignore_for_file: avoid_print
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:testapi/courses.dart';
Future fetchCourses() async {
String username = "walid.beday";
String password = "wordpress application password";
String credentials = "Basic ${base64.encode(
utf8.encode("$username:$password"),
)}";
print(credentials);
final response = await http.get(
Uri.parse("https://example.com/wp-json/wp/v2/sfwd-courses"),
headers: {"authorization": credentials},
);
final responseJson = jsonDecode(response.body);
if (response.statusCode == 200) {
for (var course in responseJson) {
print(course["title"]["rendered"]);
);
}
print("Good connetiopn".toUpperCase());
} else {
("bad connection".toUpperCase());
}
}
and this is class Course
// ignore_for_file: public_member_api_docs, sort_constructors_first
class Courses {
String courseTitle;
int courseId;
Courses({
required this.courseTitle,
required this.courseId,
});
}
I dont know how to take the value from json and add them to course class and return this class in listview builder, here is main.dart
import 'package:flutter/material.dart';
import 'package:testapi/courses.dart';
import 'config.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
var courses = [];
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.red),
useMaterial3: true,
),
home: Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).appBarTheme.backgroundColor,
elevation: 20,
title: const Text("Test Api"),
),
floatingActionButton: const FloatingActionButton(
onPressed: fetchCourses,
),
body: ListView.builder(
itemCount: ,
itemBuilder: (BuildContext context, int index) {
return Courses(courseTitle: courseTitle, courseId: courseId);
},
),
),
);
}
}
I dont know what how to ListView.builder to fetch courses
I tried this but didnt work
// ignore_for_file: avoid_print
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:testapi/courses.dart';
Future fetchCourses() async {
String username = "walid.beday";
String password = "wordpress application password";
String credentials = "Basic ${base64.encode(
utf8.encode("$username:$password"),
)}";
print(credentials);
final response = await http.get(
Uri.parse("https://example.com/wp-json/wp/v2/sfwd-courses"),
headers: {"authorization": credentials},
);
final responseJson = jsonDecode(response.body);
if (response.statusCode == 200) {
for (var course in responseJson) {
print(course["title"]);
return Courses(
courseId: responseJson["id"],
courseTitle: responseJson["title"]["rendered"],
);
}
print("Good connetiopn".toUpperCase());
} else {
("bad connection".toUpperCase());
}
}
2
Answers
I get an error in app
When I print(responseJson)
i get this json
You probably want to do something like this…
First, create a constructor factory on your class (note that I had to make some assumptions about the data when I was casting the json variable):
Then, change your return type to be a
Future<List<Courses>>
, create an empty list, and populate it with each item you build (note that I did not check your method for accuracy or other issues – I just created the list, cast the results into newCourses
classes, added them to the list, and returned the list):Next, you need to properly invoke your method using a
FutureBuilder
and doing some basic state handling: