I have this response from a restapi and wnat to access the replies inside of comments i do have the model from quicktype.io but don't know how to iterate and fetch the data.
"data": {
"_id": "61ee65fd92a48c7b10779f24",
"topicName": "Test Topic",
"description": "<p>Test Discussion</p>",
"createdByName": "Admin",
"comments": [
{
"_id": "622740a70fdfbb1bdd00232b",
"comment": "post commnet test",
"commentedById": "611cb5ecaf1a1bbc858d4d13",
"user": [
{
"title": "Mr",
"firstName": "John",
"lastName": "Cart",
"userID": "USER1000022",
"_id": "611cb5ecaf1a1bbc858d4d13"
}
],
"replies": []
},
{
"_id": "620d05382773643acd49177b",
"comment": "test message",
"commentedById": "611cb5ecaf1a1bbc858d4d13",
"commentedByName": "Mr. John Cart",
"user": [
{
"title": "Mr",
"firstName": "John",
"lastName": "Cart",
"userID": "USER1000022",
"_id": "611cb5ecaf1a1bbc858d4d13"
}
],
"replies": [
{
"_id": "6227351b0fdfbb099800232a",
"comment": "test msg",
"commentedById": "611cb5ecaf1a1bbc858d4d13",
"commentedByName": "Mr, john cart",
"replyUser": [
{
"title": "Mr",
"firstName": "John",
"lastName": "cart",
"userID": "USER1000022",
"_id": "611cb5ecaf1a1bbc858d4d13"
}
]
}
],
},
any help or documentations/ suggestions / guides would be helpfull
Thank you
CodePudding user response:
var object= json.decode(response.body)
object variable must be in repeated syntax
print(object["data"]["comments"][index]["replies"]
CodePudding user response:
Fetch data from the internet
This recipe uses the following steps:
- Add the http package.
- Make a network request using the http package.
- Convert the response into a custom Dart object.
- Fetch and display the data with Flutter.
dependencies: http: <latest_version>
import the http package
import 'package:http/http.dart' as http;
Additionally, in your AndroidManifest.xml file, add the Internet permission.
<!-- Required to fetch data from the internet. -->
<uses-permission android:name="android.permission.INTERNET" />
Make a network request
Future<YourModel> fetchData() async {
final response = await http
.get(Uri.parse('yourapiurl'));
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
return YourModel.fromJson(jsonDecode(response.body));
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load data');
}
}
Fetch the data
class _MyAppState extends State<MyApp> {
late Future<YourModel> yourAlbum;
@override
void initState() {
super.initState();
yourModel = fetchData();
}
// ···
}
Display the data
FutureBuilder<YourModel>(
future: futureModel,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data!.title);
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
// By default, show a loading spinner.
return const CircularProgressIndicator();
},
)