1
0
mirror of https://github.com/nisrulz/flutter-examples.git synced 2026-08-25 09:13:00 +00:00
Files
flutter-examples/using_http_get/lib/example.dart
Nishant Srivastava 780c0f1dbb refactor: split app wrapper from focused example code (single-file apps)
Convert 20 more single-file apps to the validated pattern: lib/main.dart
holds only the runApp + MaterialApp bootstrap, while a new lib/example.dart
holds the full screen (Scaffold, AppBar) and the focused example code.

Apps: enabling_splash_screen, getx_counter_app, image_from_network,
infinite_list, load_local_image, load_local_json, persist_key_value,
push_notifications, sliver_app_bar_example, stateless_widgets, tic_tac_toe,
tip_calculator, using_alert_dialog, using_edittext, using_expansionpanel,
using_http_get, using_interactiveviewer, using_snackbar, using_stepper,
using_theme
2026-08-18 00:41:30 +02:00

90 lines
2.6 KiB
Dart

import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
// Example: fetch JSON data over HTTP GET and display the results in a list.
class Example extends StatefulWidget {
const Example({super.key});
@override
State<Example> createState() => _ExampleState();
}
class _ExampleState extends State<Example> {
final String url = "https://swapi.dev/api/people";
List? data;
// Function to get the JSON data
Future<String> getJSONData() async {
var response = await http.get(
// Encode the url
Uri.parse(url),
// Only accept JSON response
headers: {"Accept": "application/json"});
// Logs the response body to the console
print(response.body);
// To modify the state of the app, use this method
setState(() {
// Get the JSON data
var dataConvertedToJSON = json.decode(response.body);
try {
if (dataConvertedToJSON.statusCode == 200) {
// Extract the required part and assign it to the global variable named data
data = dataConvertedToJSON['results'];
}
} catch (e) {
print(dataConvertedToJSON.statusCode);
}
});
return "Successfull";
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Retrieve JSON Data via HTTP GET"),
),
// Create a Listview and load the data when available
body: ListView.builder(
itemCount: data == null ? 0 : data!.length,
itemBuilder: (BuildContext context, int index) {
return Container(
child: Center(
child: Column(
// Stretch the cards in horizontal axis
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Card(
child: Container(
padding: const EdgeInsets.all(15.0),
child: Text(
// Read the name field value and set it in the Text widget
data![index]['name'],
// set some style to text
style: const TextStyle(
fontSize: 20.0, color: Colors.lightBlueAccent),
),
),
)
],
)),
);
}),
);
}
@override
void initState() {
super.initState();
// Call the getJSONData() method when the app initializes
getJSONData();
}
}