O framework full-stack para Flutter: modelos em estilo Eloquent, autenticação, roteamento, tempo real e pagamentos, prontos para todos os dispositivos.
Orientação gerada a partir de informações públicas. Apenas para referência.
Magic é um framework Flutter full-stack que simplifica o desenvolvimento de aplicativos com recursos embutidos como modelos no estilo Eloquent, autenticação, roteamento, capacidades em tempo real e integração de pagamentos. Projetado para implantação multiplataforma, permite que desenvolvedores criem aplicativos escaláveis para Android, iOS, Linux, macOS e Windows com configuração mínima. O framework simplifica a lógica do backend e as interações do frontend, permitindo prototipagem rápida e aplicativos prontos para produção. Com foco na experiência do desenvolvedor, o Magic reduz o código boilerplate e acelera o tempo até o mercado.
Casos de uso
Construindo aplicativos completos em Flutter
Implementação de autenticação de usuário
Criando recursos em tempo real
Integração de pagamentos
Implantação de aplicativo multiplataforma
Principais recursos
Modelos de dados no estilo Eloquent
Autenticação embutida
Sincronização de dados em tempo real
Processamento de pagamento
Suporte multiplataforma
Indicado para
desenvolvedores full-stack Flutter
Startups construindo MVPs
Aplicativos que exigem atualizações em tempo real
Projetos que precisam de autenticação e pagamentos integrados
Aplicativos móveis e de desktop multiplataforma
Considerações
Requer conhecimento de conceitos de full-stack
Dependente de serviços externos para alguns recursos
Pode ser necessário personalizar para lógica de negócios complexa
Curva de aprendizado para novos usuários
Suporte limitado da comunidade em comparação com pacotes principais
README original
Snapshot do README original do repositório-fonte vinculado. Consulte o repositório para o conteúdo mais recente.
Magic
The full-stack framework for Flutter: Eloquent-style models, auth, routing, realtime and payments, wired and ready on every device.
The core package carries the container, facades, models over your REST API, routing without BuildContext, auth, validation, forms, events, cache, localisation and test fakes. Realtime, payments, SQLite, notifications, deep links, social sign-in, encryption, file picking and the starter kit are official plugins, and payments run through Stripe on the web and store purchase on iOS and Android, with no rail on desktop. Familiar to Laravel developers: the vocabulary carries over.
Android, iOS, macOS, Windows, Linux and the web. Vault keeps secrets in the platform's secure storage.
Requires
Dart >=3.13, Flutter >=3.47
Dependencies
wind_kit, material_ui, dowel, dio, go_router, flutter_secure_storage and a few more, see Dependencies
License
MIT
Install
flutter pub add magic
dart run magic:dowel magic:install
Magic ships its own dowel executable, so the command works as soon as magic is a dependency, with no global activation. magic:install adds wind_kit, material_ui and dowel to your pubspec.yaml, writes the config files, the service providers, the .env files and a lib/main.dart that calls Magic.init(). It also scaffolds bin/dispatcher.dart, so plugin commands resolve.
flutter pub add magic installs core only. Realtime, payments, SQLite, notifications, encryption, the file picker and the rest of the plugin family are separate packages. Add one with flutter pub add <package>, then dart run magic:dowel plugin:install <package>.
A taste of Magic
A model maps a REST resource, a controller loads it and renders each state, a route serves the screen:
fetchList drives loading, success, error and empty for you, and navigation, auth and validation work from anywhere without a BuildContext: MagicRoute.toNamed('user.show', params: {'id': '1'}), Auth.check(), Validator.make(data, rules).passes().
The sections below use the User model above; any other class a sample names (PaymentGateway, HomePage, Post) is the app's own.
Container and service providers
Services live in a string-keyed container. A provider binds them in register() and wires them up in boot(); Magic.init() registers every provider in app.providers, then boots them in that order.
A factory binding: a new instance per make, or one cached instance with shared: true
Magic.singleton(key, factory)
A lazy shared instance
Magic.make<T>(key), Magic.bound(key)
Resolve a service; check a key
Magic.findOrPut<T>(builder), Magic.find<T>()
The controller registry, keyed by type
ServiceProvider.register(), boot()
Bind synchronously; initialise asynchronously, after every provider registered
Fails when: make reads a key nothing bound (it throws, naming the key); a provider is missing from app.providers (it never runs); register() resolves another provider's service, which may not be bound yet (do it in boot()).
Facades
Static facades front the container services, so no call needs a BuildContext.
finalMagicResponse response = awaitHttp.get('/plans', query: {'page': 1});
if (response.successful) {
awaitCache.put('plans', response.data, ttl: constDuration(minutes: 5));
}
Log.info('Loaded plans for ${Config.get<String>('app.name')}');
Facade
Surface
Auth, Gate
Sign-in state and guards; abilities and policies
Http
get, post, put, delete, upload and the RESTful index, show, store, update, destroy, answering MagicResponse
Navigation without context; flash data across one navigation
Storage, Vault, Launch
Files, secure storage, opening URLs, mail, phone and SMS
Fails when: a facade runs before await Magic.init() returns (its service is not bound yet); code calls Http.patch (there is no patch verb; put and update send PUT, which suits only an endpoint that accepts it, and a Laravel endpoint that takes only PATCH accepts Http.post with '_method': 'PATCH' in the body); Launch runs without LaunchServiceProvider in app.providers.
Models
A model is an active record over a REST resource; useLocal adds SQLite through magic_local_storage.
finalUser? user = awaitUser.find(1);
if (user != null) {
user.fill({'name': 'Ada'}, strict: true);
if (!await user.save()) {
Log.warning('Not saved: ${user.validationErrors}');
}
}
Member
Does
table, resource, fillable, casts, relations
Describe the model; casts include datetime (to Carbon), json, bool, int, double, EnumCast and ListCast
get<T>(key), set(key, value)
Typed attribute access for the model's own getters and setters
Mass assignment through fillable; hydration that bypasses it
save(), delete()
Persist through the API (and the local store with useLocal); save() answers true when any leg succeeded, and validationErrors holds the remote leg's field errors
InteractsWithPersistence.findById, allModels
The reads behind a model's static find and all
toMap(), toJson(), hidden, appends
Serialisation
Fails when: a relation was not nested in the payload (there is no lazy load and no with(), so it reads null); fill without strict meets a key outside fillable (it is dropped silently, strict: true throws MassAssignmentException); get<T> meets a value of another type (it answers null); a useLocal model has no magic_local_storage (it throws StateError); a hybrid model (useLocal and useRemote) whose API refuses the save while the local write succeeds answers true with validationErrors filled, so check the errors even after a true; when the API fails without field errors (a 500, a transport error) it also answers true, with validationErrors empty, and lastRemoteResponse tells you: the failed response, statusCode 0 for no readable answer, or null when the driver threw.
Routing and middleware
Routes resolve to widgets on go_router, and middleware runs on navigation, not on an HTTP request.
Fails when: a route, layout or observer is added after the router is built (the first read of MagicRoute.config, which Magic.init() does last) and it throws StateError; a route names a middleware alias nothing registered (Magic.init throws, naming the route); a drill-down route expects a swipe back after to() (it replaces the page list, mark the route .stacked()).
Auth and authorisation
The app makes the login call; Auth stores the token in Vault and restores the session on the next cold start. Gate checks abilities on the client.
Abilities, a super-admin bypass, checks, model policies
MagicCan, MagicCannot
Widgets shown or hidden by an ability
Fails when: no user factory is set before AuthServiceProvider boots (the stored session is not restored; set it in AppServiceProvider.boot() and list that provider first); an ability is undefined, nobody is signed in or the callback throws (Gate denies without an error). Gate is advisory: the backend authorises again.
Validation and forms
Rules are classes, messages are translation keys, and a 422 from a Laravel backend lands on the same fields.
Required, Email, Min, Max, Confirmed, In, Unique and more
Rules; a custom rule extends Rule
FormRequest
authorize(), prepared(), rules() and validate(data) in one class
MagicFormData, MagicForm
Form state with a text controller per field, and the widget that shows server errors
ValidatesRequests
A controller mixin: validateRequest, handleApiError(response), hasError, getError
Fails when: FormRequest.validate drops a key that rules() does not name, even one prepared() added; a custom rule's message() returns a sentence instead of a key (its messages override never matches); Unique meets a network error (it passes, the backend has the last word).
Events
In-app publish and subscribe: not queued and not transaction-aware.
// In a provider's register():Event.listen<UserRegistered>(() => SendWelcomeMail());
// Anywhere, once the user exists:awaitEvent.dispatch(UserRegistered(user));
Member
Does
Event.listen<T>(factory)
Register a listener factory for event type T
Event.dispatch(event)
Run every listener of the event's type, in order
Event.listenAny(callback)
Observe every event; answers an unsubscribe function
BaseEventServiceProvider
Maps event types to listener factories in one place
Fails when: listen is called without a type argument (Dart infers MagicEvent and no event matches); a listener is registered in boot() (an event dispatched while the auth guard boots is missed, register in register()).
Cache
A cache with a time-to-live, file-backed by default.
finalList<dynamic> plans = awaitCache.remember<List<dynamic>>(
'plans',
constDuration(hours: 1),
() async {
finalMagicResponse response = awaitHttp.get('/plans');
// Throwing keeps a failed answer out of the cache: remember stores only// what the callback returns.if (!response.successful) throwStateError('Plans failed: ${response.statusCode}');
return response.data asList<dynamic>;
},
);
Fails when: CacheServiceProvider is not in app.providers (the cache key is unbound); cache.driver is not a CacheStore (it throws); remember<T> finds a cached value of another type (the cast throws); a remember callback returns a failed response's body (it is cached for the whole TTL, so throw instead).
Localisation
JSON catalogues under assets/lang/, Laravel-style keys and pluralisation, and a locale switch at runtime.
Lang.setLocale, detectLocale, detectAndSetLocale, current
Switch and read the locale
Fails when: a key is missing (it answers the key itself, no error); LocalizationServiceProvider is not registered (no catalogue loads); trans runs before the translations load (check Lang.isLoaded).
Testing
package:magic/testing.dart resets the framework between tests and fakes the facades in memory, with no mock library.
Fails when: a test skips the reset (state leaks and a test passes for the wrong reason); a plain test reaches MagicRoute.to (MagicTest.init() builds no router, so cover navigation in a widget test).
The plugin family
Magic core stays small, and realtime, payments and the other layers below are official plugins, not part of flutter pub add magic. Each plugin adds one layer and has its own page.
wind_kit for styling, re-exported so WDiv and WText come with the barrel; material_ui for the MaterialApp that MagicApplication builds; dowel for the CLI behind dart run magic:dowel; dio for the Http facade; go_router for routing; flutter_secure_storage for Vault; flutter_dotenv for .env; intl and jiffy for localisation and dates; logger for logging; url_launcher for Launch. Core has no code generation and no dependency on the dev tools: magic_devtools carries those adapters.
Links
Documentation: installation, the container, facades, routing, Eloquent, security and testing