This app fetches a to-do item title from a remote API and shows it on the screen. It starts with 'Loading...' and updates when data arrives.
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _title = 'Loading...';
@override
void initState() {
super.initState();
fetchTitle();
}
Future<void> fetchTitle() async {
final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/todos/1'));
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
setState(() {
_title = data['title'];
});
} else {
setState(() {
_title = 'Failed to load';
});
}
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('API Call Example')),
body: Center(child: Text(_title, style: TextStyle(fontSize: 24))),
),
);
}
}