This app shows a button. When pressed, it fetches a post from the internet and shows the text on screen.
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String data = 'Press the button to fetch data';
Future<void> fetchData() async {
final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts/1'));
if (response.statusCode == 200) {
setState(() {
data = response.body;
});
} else {
setState(() {
data = 'Failed to load data';
});
}
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('HTTP Package Example')),
body: Padding(
padding: EdgeInsets.all(16),
child: Column(
children: [
Expanded(child: SingleChildScrollView(child: Text(data))),
ElevatedButton(
onPressed: fetchData,
child: Text('Fetch Data'),
),
],
),
),
),
);
}
}