Share code with Flutter
Put a @Dto class in a shared Dart package, so the Dox server and the Flutter app check input with the same rules and error messages.
The app checks the form, so the user sees an error at once. The server checks the same input again, because it can not trust the client. The generated DTO code is pure Dart, so it runs in Flutter and on the web.
What you need
- A Dox app (
dox create server). Here it is in theserverfolder. - A Flutter app (
flutter create app). Here it is in theappfolder.
The layout
The three parts live next to each other in one folder:
The app and the server use the same DTO:
- app: Flutterchecks the form
- server: Doxchecks the request
1. The shared package
Make a plain Dart package for the DTOs:
name: blog_shared
description: DTOs shared by the Dox server and the Flutter app.
version: 0.1.0
publish_to: none
environment:
sdk: ^3.13.0
Add the packages:
Now write the DTO. Import dox_validation, not dox_core, because dox_core does not run in Flutter:
import 'package:dox_validation/dox_validation.dart';
part 'save_blog.g.dart';
/// A new blog post. The server and the app check it with the same rules.
@Dto()
class SaveBlog {
@Trim()
@Length(min: 3, max: 255)
final String title;
@Trim()
@MinLength(10)
final String description;
const SaveBlog({required this.title, required this.description});
static const DtoSchema<SaveBlog> schema = $SaveBlogDto;
}
Export the DTOs. Also export dox_validation, so the app gets ParseResult and ValidationException from the same import:
export 'package:dox_validation/dox_validation.dart';
export 'src/save_blog.dart';
Generate the code:
This writes lib/src/save_blog.g.dart and lib/generated/dtos.g.dart, the list of every DTO in the package. Commit both files, so the Flutter app does not need to run the generator.
@Unique and @Exists come from dox_orm, which the app can not import. Check them on the server only.
2. The Dox server
Add the shared package to the dependencies of the server:
dependencies:
# ... the packages of the new app stay
blog_shared:
path: ../packages/blog_shared
Run dart pub get.
Add the DTO list of the shared package to the dtos list of AppConfig:
import 'package:blog_shared/generated/dtos.g.dart' as shared;
import 'package:dox_core/dox_core.dart';
import 'package:server/generated/dtos.g.dart';
AppConfig appConfig = AppConfig(
// ...
dtos: <DtoSchema<Object>>[...dtos, ...shared.dtos],
);
The controller asks for SaveBlog like any other DTO. Bad input gets 422:
import 'package:blog_shared/blog_shared.dart' show SaveBlog;
import 'package:dox_core/dox_core.dart';
@Inject()
class BlogController {
Future<Map<String, dynamic>> store(SaveBlog body) async {
// body.title is already trimmed and checked.
return <String, dynamic>{'title': body.title, 'saved': true};
}
}
Use show SaveBlog in server code, because dox_core and blog_shared both export a ValidationException class.
Add the route:
A bad request gets the errors as {"key": "message"}:
POST /api/blogs {"title": "ab", "description": "short"}
422 {"title":"The title must be between 3 and 255 characters",
"description":"The description must be at least 10 characters"}
3. The Flutter app
Add the shared package to the app:
name: app
publish_to: none
environment:
sdk: ^3.13.0
dependencies:
flutter:
sdk: flutter
http: ^1.6.0
blog_shared:
path: ../packages/blog_shared
The widget checks the form with SaveBlog.schema.safeParse(), and sends only good input. result.errors has the same shape as the 422 body of the server:
import 'dart:convert';
import 'package:blog_shared/blog_shared.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class NewBlogForm extends StatefulWidget {
const NewBlogForm({super.key});
@override
State<NewBlogForm> createState() {
return _NewBlogFormState();
}
}
class _NewBlogFormState extends State<NewBlogForm> {
final TextEditingController _title = TextEditingController();
final TextEditingController _description = TextEditingController();
Map<String, String> _errors = <String, String>{};
Future<void> _submit() async {
ParseResult<SaveBlog> result =
SaveBlog.schema.safeParse(<String, dynamic>{
'title': _title.text,
'description': _description.text,
});
if (!result.success) {
setState(() {
_errors = result.errors;
});
return;
}
http.Response response = await http.post(
Uri.parse('https://api.example.com/api/blogs'),
headers: <String, String>{'Content-Type': 'application/json'},
body: jsonEncode(SaveBlog.schema.toMap(result.value!)),
);
setState(() {
_errors = response.statusCode == 422
? Map<String, String>.from(jsonDecode(response.body) as Map)
: <String, String>{};
});
}
@override
void dispose() {
_title.dispose();
_description.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
TextField(
controller: _title,
decoration: InputDecoration(
labelText: 'Title', errorText: _errors['title']),
),
TextField(
controller: _description,
decoration: InputDecoration(
labelText: 'Description',
errorText: _errors['description']),
),
ElevatedButton(onPressed: _submit, child: const Text('Save')),
],
);
}
}
Other schema methods
The schema has more methods than safeParse:
parsethrows aValidationExceptionwhen the input is bad.toMapgives the JSON map to send.toJsonSchemagives the JSON Schema of the DTO.
If the DTO has an async validate() method, use safeParseAsync or parseAsync.
Next steps
- Validation: all the rules.
- dox_validation: all the schema methods.