Mobile development · Intermediate · 24 min
Call a REST API from Flutter and parse the JSON safely
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · Flutter 3.50.1 · Dart 3.14 · http 1.6.0
You will build a Flutter screen that loads practitioners from a clinic API with http 1.6, parses the JSON into immutable models with Dart 3 patterns, turns timeouts, bad statuses and broken JSON into typed errors the patient can act on, and proves it all with MockClient tests and a test against a local Dart server.
On this page
Most Flutter apps talk to a server, and most tutorials on the subject stop at the happy path: http.get, jsonDecode, and a json['name'] that the compiler cannot check. That code works on the developer's Wi-Fi. It fails on a patient's phone when the clinic server is restarting, when a hotel captive portal answers with an HTML login page, when a field the app expects is missing, or when the connection is so slow the screen spins forever.
In this tutorial you build the data layer and one screen for a clinic booking app. A ClinicRepository calls GET /api/practitioners with the http package, checks the status, and decodes the reply into immutable Practitioner objects using Dart 3 patterns instead of dynamic. Every way the call can fail becomes one of four typed errors, and the screen shows a message the patient can act on, with a Try again button. You test the parsing and the repository with http's MockClient, so no network is needed, and finish with tests against a small Dart server running on your own machine.
Step 1 · Create the project and add http
Make a demo folder, create an app in it and add the http package. The caret range accepts any 1.x release from 1.6.0 upwards, so a 2.0 with breaking changes cannot arrive by surprise. The same command adds material_ui: since Flutter 3.47 the Material widgets live in that package, and package:flutter/material.dart is deprecated:
mkdir -p ~/clinic-api-demo
cd ~/clinic-api-demo
flutter create clinic_api
cd clinic_api
flutter pub add "http:^1.6.0" material_uiflutter create writes a counter app and a test for it. You replace the app, so delete that test now; it would fail once the counter has gone:
rm test/widget_test.dartCheck it worked
grep -E 'http:|material_ui:' pubspec.yamlThe lines http: ^1.6.0 and material_ui: appear under dependencies, and pubspec.lock now pins http at 1.6.0 or a later 1.x.
Step 2 · Run a local clinic API to call
You need a server that behaves like a real one, including its bad days. Write one with dart:io, so it needs no packages. It answers /api/practitioners with JSON, and two path prefixes make it misbehave on purpose: anything under /slow/ waits three seconds first, and anything under /broken/ answers 503 Service Unavailable. Put it in tool/, where Flutter does not bundle it into the app:
mkdir -p tool
cat > tool/clinic_server.dart <<'DART'
import 'dart:convert';
import 'dart:io';
const practitioners = [
{
'id': 'folake',
'name': 'Dr Fọlákẹ́ Adéyẹmí',
'specialty': 'General practice',
'languages': ['English', 'Yorùbá'],
'acceptingPatients': true,
},
{
'id': 'kofi',
'name': 'Dr Kofi Mensah',
'specialty': 'Paediatrics',
'languages': ['English', 'Twi'],
'acceptingPatients': true,
},
{
'id': 'wanjiru',
'name': 'Wanjiru Kamau',
'specialty': 'Physiotherapy',
'languages': ['English', 'Kiswahili'],
'acceptingPatients': false,
},
];
Future<void> main() async {
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 8085);
stdout.writeln('Clinic API listening on http://127.0.0.1:8085');
server.listen((request) async {
final path = request.uri.path;
final response = request.response
..headers.contentType = ContentType.json
..headers.set('Access-Control-Allow-Origin', '*');
if (path.startsWith('/slow/')) {
await Future<void>.delayed(const Duration(seconds: 3));
}
if (path.startsWith('/broken/')) {
response.statusCode = HttpStatus.serviceUnavailable;
response.write(jsonEncode({'error': 'maintenance'}));
} else if (path.endsWith('/api/practitioners')) {
response.write(jsonEncode({'practitioners': practitioners}));
} else {
response.statusCode = HttpStatus.notFound;
response.write(jsonEncode({'error': 'not found'}));
}
await response.close();
});
}
DARTContentType.json sends application/json; charset=utf-8, so the Yorùbá tone marks in Dr Fọlákẹ́ Adéyẹmí's name travel as UTF-8. Names like this are the norm for many of your users, and they are the quickest way to catch a client that decodes text with the wrong character set. server.listen handles each request as it arrives, so a slow request does not hold up the others. The Access-Control-Allow-Origin header lets the app call it from Chrome later.
Start it in a second terminal, from the clinic_api folder, and leave it running:
cd ~/clinic-api-demo/clinic_api
dart run tool/clinic_server.dartThe terminal prints Clinic API listening on http://127.0.0.1:8085. This server has no authentication and keeps its data in code; it exists only for practice.
Check it worked
Back in your first terminal, call the three behaviours with curl. -i shows the status line and headers:
curl -s http://127.0.0.1:8085/api/practitioners
curl -si http://127.0.0.1:8085/broken/api/practitioners | head -n 1
curl -s http://127.0.0.1:8085/nothing-hereThe first command prints the JSON object with three practitioners, the second shows HTTP/1.1 503 Service Unavailable, and the third prints {"error":"not found"}. If you want more practice reading responses like these, see test an API with curl.
Step 3 · Model the JSON with immutable classes and patterns
jsonDecode returns dynamic. The tempting next line looks like this:
final data = jsonDecode(response.body);
final name = data['practitioners'][0]['name'];It compiles, because the compiler checks nothing on a dynamic value. If the server renames a field, sends null, or replies with a list instead of an object, the app finds out at run time with a NoSuchMethodError or a TypeError deep inside a widget build. The fix is to check the shape once, at the edge, and hand the rest of the app a class with real types.
Dart 3 map patterns do that check in one expression. A pattern such as {'name': String name} matches only if the value is a map, the key is present and its value is a String, and it binds name with that type. Keys the pattern does not name are ignored, so the server can add fields without breaking older app versions.
cat > lib/practitioner.dart <<'DART'
import 'dart:convert';
/// One practitioner, as the app uses it. Every field is final and typed.
final class Practitioner {
const Practitioner({
required this.id,
required this.name,
required this.specialty,
required this.languages,
required this.acceptingPatients,
});
final String id;
final String name;
final String specialty;
final List<String> languages;
final bool acceptingPatients;
/// Throws a [FormatException] unless [json] has exactly the shape we need.
factory Practitioner.fromJson(Object? json) {
return switch (json) {
{
'id': String id,
'name': String name,
'specialty': String specialty,
'languages': List<Object?> languages,
'acceptingPatients': bool acceptingPatients,
} =>
Practitioner(
id: id,
name: name,
specialty: specialty,
languages: List.unmodifiable(languages.map(_requireString)),
acceptingPatients: acceptingPatients,
),
_ => throw FormatException('Not a practitioner: $json'),
};
}
}
String _requireString(Object? value) {
return switch (value) {
String text => text,
_ => throw FormatException('Expected a string, got $value'),
};
}
/// Parses the body of GET /api/practitioners.
List<Practitioner> parsePractitioners(String body) {
return switch (jsonDecode(body)) {
{'practitioners': List<Object?> items} => List.unmodifiable([
for (final item in items) Practitioner.fromJson(item),
]),
_ => throw const FormatException('Expected an object with a "practitioners" list'),
};
}
DARTThree choices in that file are worth copying into your own models:
- One failure type.
jsonDecodethrowsFormatExceptionfor text that is not JSON, and the patterns throw the same type for JSON of the wrong shape. The caller catches one exception for every kind of bad data. - Lists are checked item by item.
List<Object?> languagesonly proves there is a list._requireStringchecks every entry, so["English", 3]fails here instead of later in aTextwidget. - Nothing can change after parsing. The fields are
finaland the lists areList.unmodifiable, so a widget cannot quietly edit data another widget is showing.
When models grow
Hand-written patterns suit a handful of small models. Once you have dozens of classes, nested objects and renamed keys, generate the code instead. json_serializable (6.15 at the time of writing) reads a class annotated with @JsonSerializable() and, when you run dart run build_runner build, writes fromJson and toJson functions into a .g.dart part file. The generated code casts each field, so a wrong type still fails at parse time rather than in the UI. Whichever you use, keep parsing inside the data layer and let widgets see only typed classes.
Check it worked
flutter analyze lib/practitioner.dartThe analyser ends with No issues found!.
Step 4 · Turn every failure into a typed error
A network call can fail in four ways the screen cares about: no answer in time, no connection at all, an answer with the wrong status, or an answer the app cannot read. Give each one a class. Making the base class sealed means a switch over it must handle all four, and the compiler tells you if a fifth is added and a screen forgets it:
cat > lib/clinic_api_exception.dart <<'DART'
/// Everything that can go wrong when calling the clinic API.
sealed class ClinicApiException implements Exception {
const ClinicApiException(this.message);
final String message;
@override
String toString() => '$runtimeType: $message';
}
/// The server did not answer within the timeout.
final class TimeoutFailure extends ClinicApiException {
TimeoutFailure(Duration after)
: super('no response within ${after.inMilliseconds} ms');
}
/// The request never reached the server: no network, DNS failure, refused.
final class NetworkFailure extends ClinicApiException {
const NetworkFailure(super.message);
}
/// The server answered with a status other than 200.
final class HttpStatusFailure extends ClinicApiException {
HttpStatusFailure(this.statusCode) : super('HTTP $statusCode');
final int statusCode;
}
/// The server answered 200, but the body was not the JSON we expect.
final class BadDataFailure extends ClinicApiException {
const BadDataFailure(super.message);
}
DARTNow the repository. It takes an http.Client instead of creating one, so tests can pass in a MockClient and the app can share one client for every call:
cat > lib/clinic_repository.dart <<'DART'
import 'dart:async';
import 'dart:convert';
import 'package:clinic_api/clinic_api_exception.dart';
import 'package:clinic_api/practitioner.dart';
import 'package:http/http.dart' as http;
class ClinicRepository {
ClinicRepository({
required this.client,
required Uri baseUrl,
this.timeout = const Duration(seconds: 15),
}) : _baseUrl = baseUrl.path.endsWith('/')
? baseUrl
: baseUrl.replace(path: '${baseUrl.path}/');
final http.Client client;
final Uri _baseUrl;
final Duration timeout;
Future<List<Practitioner>> fetchPractitioners() async {
final uri = _baseUrl.resolve('api/practitioners');
final http.Response response;
try {
response = await client
.get(uri, headers: const {'accept': 'application/json'})
.timeout(timeout);
} on TimeoutException {
throw TimeoutFailure(timeout);
} on http.ClientException catch (error) {
throw NetworkFailure(error.message);
}
if (response.statusCode != 200) {
throw HttpStatusFailure(response.statusCode);
}
try {
return parsePractitioners(utf8.decode(response.bodyBytes));
} on FormatException catch (error) {
throw BadDataFailure(error.message);
}
}
}
DARTRead it from top to bottom, because the order is the point:
- The base URL gets a trailing slash.
Uri.resolvetreatshttps://clinic.example/v1andhttps://clinic.example/v1/differently: without the slash,v1is dropped. Normalising it in the constructor removes a bug that only shows up when someone changes an environment setting. httphas no default timeout. Without.timeout, a request on a stalled mobile connection can wait for minutes..timeoutstops waiting and throwsTimeoutException; it does not close the connection. If you need the request itself cancelled,http1.5 and later can abort a request, at the cost of a few more lines.- Socket errors arrive as
ClientException. On Android, iOS and desktop,httpwraps a refused connection or a failed DNS lookup in aClientException, so oneonclause covers them. - The status is checked before the body. A 503 maintenance page or a 401 may still be valid JSON, just not the JSON you want. Checking
statusCodefirst stops the app reporting "bad data" when the real problem is the server. - The body is decoded as UTF-8 on purpose.
response.bodypicks a character set from theContent-Typeheader. Sincehttp1.4 a bareapplication/jsondefaults to UTF-8, but a server that sendstext/plainwith no charset still gets Latin-1, which turnsFọlákẹ́into garbage.utf8.decode(response.bodyBytes)is correct for any JSON API, and it throwsFormatExceptionfor invalid bytes, which the lasttryalready catches.
Fifteen seconds is a deliberate default. On a congested network a reply can take several seconds to arrive, and timing out too early sends the patient round a loop of retries that each cost data.
Check it worked
flutter analyze libThe analyser reports No issues found! for the three files in lib/ you have written so far, plus the main.dart that flutter create generated.
Step 5 · Test the parsing and the repository with MockClient
package:http/testing.dart ships MockClient, an http.Client that hands each request to a function you write and returns whatever response that function builds. Nothing touches the network.
First, shared test data. The file sits in test/ but does not end in _test.dart, so flutter test does not run it on its own. jsonResponse builds the response from UTF-8 bytes, because the plain http.Response constructor encodes its string with the character set in the headers and would reject ẹ́ if that were Latin-1:
cat > test/sample_data.dart <<'DART'
import 'dart:convert';
import 'package:http/http.dart' as http;
const practitionersJson = '''
{"practitioners": [
{"id": "folake", "name": "Dr Fọlákẹ́ Adéyẹmí", "specialty": "General practice",
"languages": ["English", "Yorùbá"], "acceptingPatients": true},
{"id": "kofi", "name": "Dr Kofi Mensah", "specialty": "Paediatrics",
"languages": ["English", "Twi"], "acceptingPatients": true},
{"id": "wanjiru", "name": "Wanjiru Kamau", "specialty": "Physiotherapy",
"languages": ["English", "Kiswahili"], "acceptingPatients": false}
]}
''';
http.Response jsonResponse(String body, [int statusCode = 200]) {
return http.Response.bytes(
utf8.encode(body),
statusCode,
headers: {'content-type': 'application/json'},
);
}
DARTThe parsing tests feed strings straight to parsePractitioners and check that every wrong shape ends in a FormatException:
cat > test/practitioner_test.dart <<'DART'
import 'package:clinic_api/practitioner.dart';
import 'package:flutter_test/flutter_test.dart';
import 'sample_data.dart';
void main() {
test('parses every field into typed, unmodifiable values', () {
final list = parsePractitioners(practitionersJson);
expect(list, hasLength(3));
expect(list.first.name, 'Dr Fọlákẹ́ Adéyẹmí');
expect(list.first.languages, ['English', 'Yorùbá']);
expect(list.last.acceptingPatients, isFalse);
expect(() => list.first.languages.add('French'), throwsUnsupportedError);
});
test('rejects a practitioner with a missing field', () {
const body = '{"practitioners": [{"id": "x", "name": "A", "specialty": "B", '
'"languages": []}]}';
expect(() => parsePractitioners(body), throwsFormatException);
});
test('rejects a language that is not a string', () {
const body = '{"practitioners": [{"id": "x", "name": "A", "specialty": "B", '
'"languages": ["English", 3], "acceptingPatients": true}]}';
expect(() => parsePractitioners(body), throwsFormatException);
});
test('rejects a body that is a bare list or not JSON at all', () {
expect(() => parsePractitioners('[]'), throwsFormatException);
expect(() => parsePractitioners('<html>Sign in to Wi-Fi</html>'), throwsFormatException);
});
}
DARTThe repository tests check the request it sends and the typed error for each failure. The slow-server test gives the repository a 100 ms timeout so it finishes quickly:
cat > test/clinic_repository_test.dart <<'DART'
import 'package:clinic_api/clinic_api_exception.dart';
import 'package:clinic_api/clinic_repository.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
import 'sample_data.dart';
ClinicRepository repositoryWith(
MockClient client, {
Duration timeout = const Duration(seconds: 2),
}) {
return ClinicRepository(
client: client,
baseUrl: Uri.parse('https://clinic.example/v1'),
timeout: timeout,
);
}
void main() {
test('sends a GET for JSON and parses the reply', () async {
late http.Request sent;
final client = MockClient((request) async {
sent = request;
return jsonResponse(practitionersJson);
});
final list = await repositoryWith(client).fetchPractitioners();
expect(sent.method, 'GET');
expect(sent.url.toString(), 'https://clinic.example/v1/api/practitioners');
expect(sent.headers['accept'], 'application/json');
expect(list.map((p) => p.id).toList(), ['folake', 'kofi', 'wanjiru']);
});
test('turns a 404 into HttpStatusFailure', () async {
final client = MockClient((_) async => jsonResponse('{"error": "not found"}', 404));
await expectLater(
repositoryWith(client).fetchPractitioners(),
throwsA(isA<HttpStatusFailure>().having((e) => e.statusCode, 'statusCode', 404)),
);
});
test('turns an HTML captive portal page into BadDataFailure', () async {
final client = MockClient(
(_) async => http.Response('<html>Sign in to Wi-Fi</html>', 200),
);
await expectLater(
repositoryWith(client).fetchPractitioners(),
throwsA(isA<BadDataFailure>()),
);
});
test('turns JSON of the wrong shape into BadDataFailure', () async {
final client = MockClient((_) async => jsonResponse('{"doctors": []}'));
await expectLater(
repositoryWith(client).fetchPractitioners(),
throwsA(isA<BadDataFailure>()),
);
});
test('turns a slow reply into TimeoutFailure', () async {
final client = MockClient((_) async {
await Future<void>.delayed(const Duration(seconds: 1));
return jsonResponse(practitionersJson);
});
final repository = repositoryWith(client, timeout: const Duration(milliseconds: 100));
await expectLater(repository.fetchPractitioners(), throwsA(isA<TimeoutFailure>()));
});
test('turns a connection failure into NetworkFailure', () async {
final client = MockClient((_) async {
throw http.ClientException('Connection refused');
});
await expectLater(
repositoryWith(client).fetchPractitioners(),
throwsA(isA<NetworkFailure>()),
);
});
}
DARTThe first test also proves the trailing-slash fix: the base URL has no slash, and the request still goes to /v1/api/practitioners.
Check it worked
flutter test test/practitioner_test.dart test/clinic_repository_test.dartThe run ends with All tests passed! after ten tests. If the URL test fails with https://clinic.example/api/practitioners, the _baseUrl line in the constructor is missing its slash handling.
Step 6 · Show the data and the errors on screen
Replace lib/main.dart. The screen keeps the request's Future in its State, so a rebuild does not fire a new request, and _reload swaps in a fresh one when the patient taps Try again. messageFor switches over the sealed error type, so each failure gets its own message and the compiler insists on all four:
cat > lib/main.dart <<'DART'
import 'package:clinic_api/clinic_api_exception.dart';
import 'package:clinic_api/clinic_repository.dart';
import 'package:clinic_api/practitioner.dart';
import 'package:material_ui/material_ui.dart';
import 'package:http/http.dart' as http;
const apiUrl = String.fromEnvironment(
'CLINIC_API_URL',
defaultValue: 'http://127.0.0.1:8085',
);
void main() {
// One client for the life of the app, so connections are reused.
final repository = ClinicRepository(
client: http.Client(),
baseUrl: Uri.parse(apiUrl),
);
runApp(ClinicApp(repository: repository));
}
String messageFor(ClinicApiException error) {
return switch (error) {
TimeoutFailure() =>
'The clinic is taking too long to answer. Check your connection and try again.',
NetworkFailure() =>
'Cannot reach the clinic. Check your mobile data or Wi-Fi and try again.',
HttpStatusFailure(statusCode: >= 500) =>
'The clinic system is having problems. Try again in a few minutes.',
HttpStatusFailure(:final statusCode) =>
'The clinic could not handle this request (error $statusCode).',
BadDataFailure() =>
'The clinic sent something this app cannot read. Try again later.',
};
}
class ClinicApp extends StatelessWidget {
const ClinicApp({super.key, required this.repository});
final ClinicRepository repository;
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Clinic',
theme: ThemeData(colorScheme: ColorScheme.fromSeed(seedColor: Colors.teal)),
home: PractitionersScreen(repository: repository),
);
}
}
class PractitionersScreen extends StatefulWidget {
const PractitionersScreen({super.key, required this.repository});
final ClinicRepository repository;
@override
State<PractitionersScreen> createState() => _PractitionersScreenState();
}
class _PractitionersScreenState extends State<PractitionersScreen> {
late Future<List<Practitioner>> _practitioners;
@override
void initState() {
super.initState();
_practitioners = widget.repository.fetchPractitioners();
}
void _reload() {
setState(() {
_practitioners = widget.repository.fetchPractitioners();
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Practitioners')),
body: FutureBuilder<List<Practitioner>>(
future: _practitioners,
builder: (context, snapshot) {
if (snapshot.connectionState != ConnectionState.done) {
return const Center(child: CircularProgressIndicator());
}
final error = snapshot.error;
if (error != null) {
final message = error is ClinicApiException
? messageFor(error)
: 'Something went wrong. Try again.';
return _ErrorView(message: message, onRetry: _reload);
}
final practitioners = snapshot.requireData;
if (practitioners.isEmpty) {
return const Center(child: Text('No practitioners are listed yet.'));
}
return ListView(
children: [
for (final p in practitioners)
ListTile(
title: Text(p.name),
subtitle: Text('${p.specialty} · ${p.languages.join(', ')}'),
trailing: p.acceptingPatients ? null : const Text('Full'),
),
],
);
},
),
);
}
}
class _ErrorView extends StatelessWidget {
const _ErrorView({required this.message, required this.onRetry});
final String message;
final VoidCallback onRetry;
@override
Widget build(BuildContext context) {
return Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(message, textAlign: TextAlign.center),
const SizedBox(height: 16),
FilledButton(onPressed: onRetry, child: const Text('Try again')),
],
),
),
);
}
}
DARTThe messages say what the patient can do, not what went wrong inside the app. A patient on prepaid data who sees "Check your mobile data" knows to look at their bundle; "SocketException: errno 111" tells them nothing. Keeping each message a single plain sentence also makes the strings easier to translate when you add Hausa, Swahili or French. Errors that are not a ClinicApiException are bugs in your own code; in a real app, report them to your crash reporting tool as well as showing the generic message.
Now a widget test. The binding that testWidgets sets up answers every real HttpClient request with status 400, so the screen gets a repository built on a MockClient instead. The second test fails the first call with a 503, taps Try again, and expects the list:
cat > test/practitioners_screen_test.dart <<'DART'
import 'package:clinic_api/clinic_repository.dart';
import 'package:clinic_api/main.dart';
import 'package:material_ui/material_ui.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:http/testing.dart';
import 'sample_data.dart';
ClinicRepository repositoryWith(MockClient client) {
return ClinicRepository(client: client, baseUrl: Uri.parse('https://clinic.example/'));
}
void main() {
testWidgets('shows a spinner, then the practitioners', (tester) async {
final client = MockClient((_) async => jsonResponse(practitionersJson));
await tester.pumpWidget(ClinicApp(repository: repositoryWith(client)));
expect(find.byType(CircularProgressIndicator), findsOneWidget);
await tester.pumpAndSettle();
expect(find.text('Dr Fọlákẹ́ Adéyẹmí'), findsOneWidget);
expect(find.text('General practice · English, Yorùbá'), findsOneWidget);
expect(find.text('Full'), findsOneWidget);
});
testWidgets('explains a server error and recovers on Try again', (tester) async {
var calls = 0;
final client = MockClient((_) async {
calls++;
return calls == 1
? jsonResponse('{"error": "maintenance"}', 503)
: jsonResponse(practitionersJson);
});
await tester.pumpWidget(ClinicApp(repository: repositoryWith(client)));
await tester.pumpAndSettle();
expect(
find.text('The clinic system is having problems. Try again in a few minutes.'),
findsOneWidget,
);
await tester.tap(find.text('Try again'));
await tester.pumpAndSettle();
expect(find.text('Wanjiru Kamau'), findsOneWidget);
expect(calls, 2);
});
}
DARTCheck it worked
flutter test test/practitioners_screen_test.dart
flutter analyzeBoth widget tests pass and flutter analyze reports No issues found! for the whole project, tests and server included.
To see the screen, keep the local API running and start the app in Chrome, passing the API address with --dart-define:
flutter run -d chrome --dart-define=CLINIC_API_URL=http://127.0.0.1:8085A spinner shows briefly, then three practitioners, with Wanjiru Kamau marked Full. Stop the app with q, run it again with --dart-define=CLINIC_API_URL=http://127.0.0.1:8085/broken and you get the server-problems message and a Try again button. On an Android emulator the host machine is 10.0.2.2, not 127.0.0.1, and Android blocks plain http:// traffic by default from Android 9, so point the app at an HTTPS API there or add a debug-only network security configuration.
Step 7 · Test against the running server
MockClient proves your code handles each response. It cannot prove that the real http.Client behaves the same: that sockets, headers, UTF-8 and timeouts all line up. A few tests against the local server close that gap. They use test, not testWidgets, so no binding is set up and the real HTTP stack is used.
The address comes from --dart-define, the same mechanism the app uses. When it is not set, the whole group is skipped, so a plain flutter test on a laptop without the server still passes:
cat > test/live_api_test.dart <<'DART'
import 'package:clinic_api/clinic_api_exception.dart';
import 'package:clinic_api/clinic_repository.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
const apiUrl = String.fromEnvironment('CLINIC_API_URL');
void main() {
group('against the local clinic server', () {
late http.Client client;
setUp(() => client = http.Client());
tearDown(() => client.close());
ClinicRepository at(String url, {Duration timeout = const Duration(seconds: 5)}) {
return ClinicRepository(client: client, baseUrl: Uri.parse(url), timeout: timeout);
}
test('fetches and parses practitioners, UTF-8 intact', () async {
final list = await at(apiUrl).fetchPractitioners();
expect(list.first.name, 'Dr Fọlákẹ́ Adéyẹmí');
expect(list.first.languages, contains('Yorùbá'));
});
test('reports a 503 as HttpStatusFailure', () async {
await expectLater(
at('$apiUrl/broken').fetchPractitioners(),
throwsA(isA<HttpStatusFailure>().having((e) => e.statusCode, 'statusCode', 503)),
);
});
test('gives up on a slow server', () async {
await expectLater(
at('$apiUrl/slow', timeout: const Duration(seconds: 1)).fetchPractitioners(),
throwsA(isA<TimeoutFailure>()),
);
});
test('reports a refused connection as NetworkFailure', () async {
await expectLater(
at('http://127.0.0.1:9').fetchPractitioners(),
throwsA(isA<NetworkFailure>()),
);
});
}, skip: apiUrl.isEmpty ? 'Pass --dart-define=CLINIC_API_URL=... to run' : false);
}
DARTPort 9 on your own machine has nothing listening on it, so the last test gets a refused connection and checks that http reports it as a ClientException your repository maps to NetworkFailure.
Check it worked
With the server still running in the second terminal:
flutter test --dart-define=CLINIC_API_URL=http://127.0.0.1:8085 test/live_api_test.dartAll four tests pass; the slow-server test takes about a second. Then run the full suite without the define:
flutter testThe output ends with something like +12 ~4: All tests passed!: twelve tests passed and the four live tests were skipped, with the reason you gave.
Step 8 · Clean up
Stop the server in the second terminal with Ctrl+C.
The next command deletes the demo folder and everything in it, including the server and the tests. Your Flutter SDK is not touched:
cd ~
rm -rf ~/clinic-api-demoCheck it worked
test ! -d ~/clinic-api-demo && echo "clinic-api-demo removed"
curl -s --max-time 2 http://127.0.0.1:8085/api/practitioners || echo "server stopped"The terminal prints clinic-api-demo removed and server stopped.
Next steps
- Move
ClinicRepositorybehind a provider and replaceFutureBuilderwith anAsyncNotifierin manage app state in Flutter with Riverpod. - Keep the practitioner list on the phone so the screen works offline in store data in a Flutter app with drift.
- Lay out a richer practitioner card in build Flutter screens from widgets, rows, columns and lists.
- Take the widget tests further, including golden images, in write Flutter unit, widget and golden tests.
Part of these paths
Related tutorials
- Build Flutter screens from widgets, rows, columns and listsYou will build a clinic services screen in Flutter 3.50 from rows, columns and a lazy list, make taps update it with setState, theme it with Material 3 and prove it works at phone size with a widget test.
- Manage app state in Flutter with RiverpodYou will move a clinic booking basket out of setState into Riverpod 3.5 providers, load practitioners with an AsyncNotifier that shows loading, error and data, and prove it with ProviderContainer unit tests and a widget test that overrides the repository.
- How to Test and Debug an API with curlYou will write a small practice API, then call it with curl 8 to read responses and headers, send JSON, send an authorization header without putting the secret on the command line, follow redirects, measure timing, set timeouts and retries, and read curl's verbose output when a request goes wrong.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials