view_model_macro 0.0.6 view_model_macro: ^0.0.6 copied to clipboard
Experimental support for ViewModel classes in Dart using pckg:macros.
ViewModel Macro #
Support for ViewModels utilities in Dart using macros.
✨ Features #
-
StateNotifier
with private state and emitter and public Stream. -
ActionNotifier
optional notifier with private emitter and public Stream. -
Dispose
automatically disposes all notifiers declared from ViewModel
🧑💻 Example #
import 'package:view_model_macro/view_model_macro.dart';
@ViewModel()
class Counter {
final StateNotifier<int> _count = StateNotifier(0);
void add() => _emitCount(_countValue + 1);
void subtract() => _emitCount(_countValue - 1);
}
void main() {
runApp(const MainApp());
}
class MainApp extends StatefulWidget {
const MainApp({super.key});
@override
State<MainApp> createState() => _MainAppState();
}
class _MainAppState extends State<MainApp> {
// Declare the ViewModel
final counter = Counter();
@override
void dispose() {
// Disposes when needed
counter.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
floatingActionButton: FloatingActionButton(
child: const Icon(Icons.add),
onPressed: () => counter.add(),
),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
// Collect the data from the stream
// and build a widget based on its data
counter.countStream.collectAsWidget(
(value) {
return Text('Count: $value');
},
),
],
),
),
),
);
}
}
🚀 Quick Start #
-
Add
package:view_model_macro
to yourpubspec.yaml
dependencies: view_model_macro: any
-
Enable experimental macros in
analysis_options.yaml
analyzer: enable-experiment: - macros
-
Use the
@ViewModel
annotation (see above example). -
Run it
flutter run --enable-experiment=macros
*Requires Dart SDK >= 3.5.0