Dart Example

Overview
This example demonstrates how to integrate ApiSorcery with Flutter/Dart projects. Flutter is Google's UI toolkit for building natively compiled applications for mobile, web, and desktop from a single codebase.
Features
- Cross-platform development: Build for iOS, Android, Web, and Desktop with one codebase
- Type-safe API clients: Generate strongly-typed Dart classes from Swagger/OpenAPI specifications
- Dio integration: Built-in support for Dio HTTP client with interceptors and error handling
- Null safety: Full support for Dart's null safety features
- Future/async support: Native async/await pattern integration
Quick Setup
1. Install ApiSorcery
bash
npm install -g autoapi2. Initialize Configuration
bash
autoapi init -l dartThis creates a .autoapirc.json configuration file:
json
{
"application": {
"language": "dart",
"outputDir": "./lib/api/auto"
},
"services": [
{
"code": "demo",
"token": "72735b33815c4e5c9c2a924a8f4907ef",
"version": 3,
"enabled": true,
"source": "https://your-api.com/swagger.json",
}
]
}3. Add Dependencies
Add the required dependencies to your pubspec.yaml:
yaml
dependencies:
dio: ^5.0.0
json_annotation: ^4.8.0
dev_dependencies:
json_serializable: ^6.6.0
build_runner: ^2.3.04. Generate API Client
bash
autoapi generate5. Use in Flutter
dart
import 'package:autoapi_example_flutter/apis/auto/demo/api_user.dart';
import 'package:autoapi_example_flutter/apis/auto/demo/httpClient/types/extension.dart';
import 'package:autoapi_example_flutter/apis/auto/demo/model.dart';
class UserService {
List<UserInfoDto>? _resultDatas;
Future<List<User>> getUsers() async {
try {
var params = UserPageQueryDto(
pagination: Pagination(
page: currentPage,
limit: 10,
)
);
var res = await ApiUser.getUserPaged(params);
_resultDatas= res.results ?? <UserInfoDto>[];
} catch (error) {
print('Failed to fetch users: $error');
rethrow;
}
}
}Platform-specific Considerations
Mobile (iOS/Android)
- Configure network permissions in platform-specific files
- Handle network security configurations for HTTP endpoints
Web
- Configure CORS properly on your backend server
- Consider web-specific limitations for certain HTTP features
Desktop
- Native networking works out of the box
- Consider platform-specific certificate handling if needed
Best Practices
- Error Handling: Implement comprehensive error handling with proper exception types
- State Management: Integrate with your preferred state management solution (Provider, Bloc, Riverpod)
- Caching: Implement appropriate caching strategies using Dio interceptors
- Testing: Write unit tests for your API clients using mockito
- Code Generation: Use
build_runnerfor JSON serialization code generation