A typed, testable networking layer on top of dio, and AI skills that write it for you

Every Flutter app has the same chore hiding in it: the network layer. A Dio instance, a base URL, an error model, a model class per endpoint with fromJson and toJson, a service that wraps the calls, and — if you are disciplined — tests with fixtures and mocks.
None of it is hard. All of it is repetitive. And in 2026 it is exactly the kind of work you should not be typing by hand.
This post covers four things:
- Why vexana: what it handles for you that plain dio doesn’t.
- Building a user list, step by step, from model to screen.
- The live playground, so you can try it without installing anything.
- The new vexana AI skills: four skills your AI assistant can follow to set up the layer, turn JSON into models, services, fakes and tests, and migrate old projects.
1. Why vexana?
vexana is a networking layer for Flutter built on dio. You keep everything dio gives you (interceptors, adapters, CancelToken, FormData) and stop rewriting the parts every app ends up needing.
Where does the name come from? Vexana is a hero in Mobile Legends, and the one I loved playing the most. When I was writing a library whose whole job is to pull data in from the network, her name was the first thing that came to mind, and it stuck.
Typed models and a sealed result
You parse into your own classes, not Map<String, dynamic>, and every request returns a NetworkResult: either NetworkSuccessResult with your data or NetworkErrorResult with the error. It's a sealed class, so a switch that forgets the error case doesn't compile.
final result = await manager.sendRequest<User, List<User>>(
'/users',
parseModel: const User(),
method: RequestType.GET,
);
final message = switch (result) {
NetworkSuccessResult(:final data) => '${data.length} users',
NetworkErrorResult(:final error) => 'Failed: ${error.description}',
};
Prefer callbacks? result.fold(onSuccess: ..., onError: ...) does the same.
Refresh tokens without the race conditions
When a request comes back 401, vexana calls your onRefreshToken callback and retries the original request with the new token. 401s are handled one at a time in a queue, so parallel requests don't race each other with half-refreshed tokens; once the token is refreshed, they all go through. If the retried request still fails after maxRetryCount attempts, onRefreshFail runs, which is where you send the user back to login.
final manager = NetworkManager<EmptyModel>(
options: BaseOptions(baseUrl: 'https://api.example.com'),
onRefreshToken: (error, newService) async {
final token = await authRepository.refresh(newService);
error.requestOptions.headers['Authorization'] = 'Bearer $token';
return error;
},
onRefreshFail: () => router.goToLogin(),
maxRetryCount: 3,
);
newService is a separate manager without the refresh interceptor, so your refresh call can't end up refreshing itself.
Your API’s error body, parsed
Give the manager your error model and error responses are parsed into it, so the UI reads error.model?.message instead of digging through a raw response.
final manager = NetworkManager<ApiError>(
options: BaseOptions(baseUrl: 'https://api.example.com'),
errorModel: const ApiError(),
);
Cache with one parameter
Pass a fileManager (LocalFile or LocalPreferences) to the manager, then add expiration to any request. Until it expires, the same request is answered from the cache: no network call, typically in about a millisecond. cache.removeAll() clears it, for example on logout.
final manager = NetworkManager<EmptyModel>(
options: BaseOptions(baseUrl: 'https://api.example.com'),
fileManager: LocalFile(), // or LocalPreferences()
);
await manager.sendRequest<User, List<User>>(
'/users',
parseModel: const User(),
method: RequestType.GET,
expiration: const Duration(minutes: 10),
);
await manager.cache.removeAll(); // e.g. on logout
No-network retry, built in
Pass noNetwork: NoNetwork(context) and a request that fails for lack of a connection shows a bottom sheet with a retry button. You can supply your own widget with customNoNetwork.
NetworkManager<EmptyModel>(
options: BaseOptions(baseUrl: 'https://api.example.com'),
noNetwork: NoNetwork(
context,
customNoNetwork: (onRetry) => TextButton(
onPressed: onRetry,
child: const Text('No connection. Try again'),
),
),
);
And the rest
A request logger (isEnableLogger), file upload with FormData, downloads with progress, CancelToken support, and it runs on mobile and on the web, including WebAssembly.
final manager = NetworkManager<EmptyModel>(
options: BaseOptions(baseUrl: 'https://api.example.com'),
isEnableLogger: true,
);
// Upload
await manager.uploadFile<Map<String, dynamic>>(
'/avatar',
FormData.fromMap({'file': await MultipartFile.fromFile(filePath)}),
);
// Download with progress
await manager.downloadFile(
'/report.pdf',
(received, total) => print('$received / $total'),
);
// Cancel
final cancelToken = CancelToken();
manager.sendRequest<User, List<User>>(
'/users',
parseModel: const User(),
method: RequestType.GET,
cancelToken: cancelToken,
);
cancelToken.cancel();
2. Let’s build a user list, step by step
Let’s fetch users from JSONPlaceholder and show them in a list.
Step 1: Describe the data
A response model extends INetworkModel<T>, which tells vexana how to parse it:
final class User extends INetworkModel<User> {
const User({this.id, this.name, this.email});
factory User.fromMap(Map<String, dynamic> json) => User(
id: json['id'] as int?,
name: json['name'] as String?,
email: json['email'] as String?,
);
final int? id;
final String? name;
final String? email;
@override
User fromJson(Map<String, dynamic> json) => User.fromMap(json);
@override
Map<String, dynamic> toJson() => {'id': id, 'name': name, 'email': email};
}Step 2: Create one manager
final INetworkManager<EmptyModel> manager = NetworkManager<EmptyModel>(
options: BaseOptions(baseUrl: 'https://jsonplaceholder.typicode.com'),
fileManager: LocalPreferences(),
);
EmptyModel means "this API has no error body to parse". LocalPreferences enables the cache.
Step 3: Fetch the users
Future<NetworkResult<List<User>, EmptyModel>> fetchUsers() =>
manager.sendRequest<User, List<User>>(
'/users',
parseModel: const User(),
method: RequestType.GET,
expiration: const Duration(minutes: 5),
);
The first type argument is the model to parse, and the second is what you get back: List<User> because /users returns a JSON array. With expiration, calls in the next five minutes come from the cache.
Step 4: Show them on screen
FutureBuilder(
future: _users, // = fetchUsers()
builder: (context, snapshot) => switch (snapshot.data) {
null => const Center(child: CircularProgressIndicator()),
NetworkSuccessResult(:final data) => ListView.builder(
itemCount: data.length,
itemBuilder: (context, index) => ListTile(
leading: CircleAvatar(child: Text('${data[index].id}')),
title: Text(data[index].name ?? ''),
subtitle: Text(data[index].email ?? ''),
),
),
NetworkErrorResult(:final error) => Center(
child: Text('Error ${error.statusCode}: ${error.description}'),
),
},
)
The switch covers loading (null), success and error, and the compiler checks that none is missing.
The result
the user list running in the browser

Notice what is not there: no jsonDecode, no try/catch around the request, no Map<String, dynamic> in the UI. The package's example has the same pattern as a complete page, with pull-to-refresh.
3. Try it in your browser: the playground
Reading about a networking library only gets you so far. The vexana playground is a Flutter Web app (compiled to WebAssembly) that runs the real package:
👉 https://vb10.github.io/vexana/
- Pick an endpoint and send a request.
- Turn on Cache, set the expiration, and send the same request again. The first call goes to the network (around 400 ms); the second comes back from the cache in about 1 ms and is marked cache hit.
- Turn on the Logger to see what vexana does under the hood.
- The Session metrics table shows count, p50, p95, max, errors and cache hits for each endpoint, with network and parse time listed separately.
It’s the quickest way to see how the options behave before you add the package to your app.
4. Let your AI assistant write the boilerplate: vexana AI skills
This is the part I’m most excited about.
You could ask an AI assistant to “write a vexana model for this JSON” and hope for the best. Sometimes you’d get the old API, sometimes a model that doesn’t compile, and almost never tests.
So vexana now ships AI skills: a set of playbooks written by the package maintainers. Each skill contains the exact vexana 6 API, templates that have been compiled and tested, and a procedure that ends by running dart analyze and flutter test. The assistant doesn't improvise the layer; it follows a playbook.
The skills are plain Markdown files (SKILL.md), so they aren't tied to one tool.
Install
Claude Code has a ready-made plugin:
/plugin marketplace add VB10/vexana
/plugin install vexana@vexana
Other AI assistants (Cursor, GitHub Copilot, Codex, Gemini CLI, …): copy the plugins/vexana/skills folder into your project and ask the assistant to follow a skill, for example "follow skills/add/SKILL.md for this JSON".
There are four skills. The examples below use Claude Code’s command syntax; with another assistant, describe the same request in plain words.
/vexana:init: set up the layer
/vexana:init base URL https://api.example.com, cache LocalFile
It reads your project first and puts files where your structure expects them. If you already have lib/product/… or lib/core/…, it uses that instead of inventing a new layout. Then it:
- adds vexana and mocktail (dev),
- creates a single AppNetworkManager whose base URL can be overridden with --dart-define=BASE_URL=...,
- generates an error model if you paste an error response,
- adds a small fixture helper for tests.
Run it twice and nothing changes. It never overwrites your files.
/vexana:add: JSON in, typed code out
/vexana:add GET /posts and GET /posts/{id}, feature post, JSON in api/posts.jsonFrom one JSON sample you get:
- a Post model (nested objects become their own classes),
- a PostService behind an IPostService interface, using sendRequest,
- the sample saved as a test fixture,
- a round-trip test: fixture → fromJson → toJson → same JSON.
@override
Future<NetworkResult<List<Post>, EmptyModel>> fetchPosts() {
return _manager.sendRequest<Post, List<Post>>(
'/posts',
parseModel: const Post(),
method: RequestType.GET,
);
}
It also handles the awkward parts of real APIs:
- Keys like class, default, 2fa or user-name become valid Dart fields (class_, default_, n2fa, userName), while the original JSON keys are kept for parsing.
- 1 in one element and 1.5 in another means double.
- An empty array or a field that is always null is typed as Object?, and the report lists it so you can decide the real type instead of the tool guessing.
/vexana:multiple-add: a whole API at once
Point it at a folder of JSON responses:
/vexana:multiple-add api_samples/ — GET /posts, GET /users, GET /comments, GET /companies
It first shows a plan (model, feature, endpoint) and waits for your OK. Then, for each feature, it writes:
- the model(s), with shared types deduplicated: if users.json has a nested company and companies.json has the same shape, you get one Company class;
- the service and its interface;
- a Fake service with a few embedded sample items, so you can build UI before the backend is ready;
- mocktail service tests (success and error for every method) and model tests.
In my test run, four JSON files became 20 files and 16 passing tests, with dart analyze reporting no issues.
/vexana:refactor: bring old projects to vexana 6
/vexana:refactor
For projects on vexana 4.x or 5.x, it:
- runs your tests first to record a baseline,
- shows the planned changes and asks before touching anything,
- bumps the dependency and fixes imports that no longer exist,
- flags the calls whose behaviour changed, with an explanation. For example, removeAll() now clears only that manager's cache, and sendPrimitive now runs through your interceptors.
At the end it compares your tests against the baseline, so a regression isn’t mistaken for a failure that was already there.
Why skills and not just a prompt?
Because the skills already contain the parts you would otherwise have to check yourself:
- The right API. The skills carry a reference of the vexana 6 surface, so there are no hallucinated methods.
- Tested templates. Every template was compiled and tested in a real Flutter project before it went into the plugin.
- Verification. Every command ends with dart analyze and flutter test, and reports failures as they are instead of claiming success.
- Safe defaults. It asks before overwriting, asks on name collisions, and waits for confirmation on bulk changes.
Get started
- 📦 flutter pub add vexana, then see pub.dev/packages/vexana
- ▶️ Playground: vb10.github.io/vexana
- 🤖 AI skills: plugins/vexana/skills. In Claude Code: /plugin marketplace add VB10/vexana, then /plugin install vexana@vexana
- ⭐ Source: github.com/VB10/vexana
If the skills save you an afternoon of boilerplate, a star on GitHub helps other Flutter developers find it. And if a skill generates something you’d write differently, open an issue: the templates are plain Markdown and easy to improve.
Stop Hand-Writing Your Flutter Network Layer: vexana 6 + AI Skills was originally published in Flutter Community on Medium, where people are continuing the conversation by highlighting and responding to this story.