请将此提及:
import dart:convert ;
import package:flutter/material.dart ;
import package:http/http.dart as http;
class PostApiFetchScreen extends StatefulWidget {
const PostApiFetchScreen({super.key});
@override
State<PostApiFetchScreen> createState() => _PostApiFetchScreenState();
}
class _PostApiFetchScreenState extends State<PostApiFetchScreen> {
final String _postApiFetchUrl = https://jsonplaceholder.typicode.com/posts ;
var postList = null;
void postApiGetMethod() async {
var response = await http.get(
Uri.parse(_postApiFetchUrl),
);
if (response.statusCode == 200) {
var responseBody = jsonDecode(response.body);
print( Response data is ${responseBody.length} );
postList = responseBody;
setState(() {});
}
}
@override
void initState() {
super.initState();
postApiGetMethod();
}
Widget postContainer({
required String title,
required String body,
required int id,
}) {
return Column(
children: [
const Divider(
height: 2,
),
postInfoTile(
key: ID ,
pair: id.toString(),
),
const SizedBox(
height: 10,
),
postInfoTile(
key: Title ,
pair: title,
),
const SizedBox(
height: 10,
),
postInfoTile(
key: Body ,
pair: body,
),
const SizedBox(
height: 3,
),
const Divider(
height: 2,
),
],
);
}
Widget postInfoTile({
required String key,
required String pair,
}) {
return Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
$key: ,
style: const TextStyle(
fontWeight: FontWeight.w900,
),
),
const SizedBox(width: 20),
Expanded(child: Text(pair)),
],
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(
Post API Consume ,
),
),
body: postList != null
? ListView.builder(
itemCount: postList.length,
itemBuilder: (context, index) => postContainer(
body: postList[index][ body ],
title: postList[index][ title ],
id: postList[index][ id ],
),
)
: const Center(
child: CircularProgressIndicator(),
),
);
}
}