import 'package:flutter/material.dart';
class RemoteDataFetchScreen extends StatefulWidget {
@override
State<RemoteDataFetchScreen> createState() => _RemoteDataFetchScreenState();
}
class _RemoteDataFetchScreenState extends State<RemoteDataFetchScreen> {
String? data;
bool isLoading = false;
String? error;
Future<String> fetchFakeApi() async {
await Future.delayed(Duration(seconds: 2));
// Simulate success or failure
bool success = true; // Change to false to test error
if (success) {
return 'Hello from API!';
} else {
throw Exception('Failed to fetch data');
}
}
void fetchData() async {
setState(() {
isLoading = true;
error = null;
data = null;
});
try {
String result = await fetchFakeApi();
setState(() {
data = result;
});
} catch (e) {
setState(() {
error = e.toString();
});
} finally {
setState(() {
isLoading = false;
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Remote Data Fetch')),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
ElevatedButton(
onPressed: fetchData,
child: Text('Fetch Data'),
),
SizedBox(height: 20),
if (isLoading) CircularProgressIndicator(),
if (data != null) Text(data!, style: TextStyle(fontSize: 18)),
if (error != null) Text(error!, style: TextStyle(color: Colors.red)),
],
),
),
);
}
}
This screen shows a button labeled 'Fetch Data'. When the user taps it, the app simulates calling an API by waiting 2 seconds and then returning a string.
While waiting, a spinning loading circle appears to show the app is busy.
If the call succeeds, the returned text is shown below the button.
If there is an error, an error message is shown in red.
This example helps understand why apps use API calls: to get fresh data from somewhere else (like a server) instead of using only data inside the app.