Coddy's Practice API
Part of the Data and the Network section of Coddy's Flutter journey. Lesson 4 of 27.
Most apps get their data from a server on the internet. In these lessons the checks cannot reach the internet, so the server lives inside your app: lib/api.dart, Coddy's practice API. Open it in the file list and read it. You cannot change it.
The part you call is one function, fetch. You give it a path, the part of a web address after the domain, and it gives you the server's answer as a String, 2 seconds later:
import 'api.dart';
final text = await fetch('/message');A real app does the same with the http package. It sends a request and waits for the answer's body, the text the server sent back:
import 'package:http/http.dart' as http;
final response = await http.get(Uri.parse('https://example.com/message'));
final text = response.body;The code around it is the same: an async function, an await, then setState with the result. Everything you build here works the same way against a real server.
Challenge
EasyTapping Load message shows Loading... and stops there. Finish loadMessage: get the text from the path /message with fetch, then show it in place of Loading....
Try it yourself
import 'package:flutter/material.dart';
import 'api.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
home: MessageScreen(),
);
}
}
class MessageScreen extends StatefulWidget {
const MessageScreen({super.key});
@override
State<MessageScreen> createState() => _MessageScreenState();
}
class _MessageScreenState extends State<MessageScreen> {
String message = 'No message yet';
Future<void> loadMessage() async {
setState(() {
message = 'Loading...';
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(message, style: const TextStyle(fontSize: 24)),
const SizedBox(height: 24),
ElevatedButton(onPressed: loadMessage, child: const Text('Load message')),
],
),
),
);
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Data and the Network
Practice on your own: Online Flutter compiler