mvu_flutter 2.0.0 mvu_flutter: ^2.0.0 copied to clipboard
State management and architecture library that allows to write Flutter Apps under MVU/The Elm Architecture approach.
import 'package:flutter/material.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:mvu_flutter/mvu_flutter.dart';
import 'package:flutter/foundation.dart';
part 'main.freezed.dart';
@freezed
class CounterModel extends Model with _$CounterModel {
const factory CounterModel(int currentValue) = _CounterModel;
}
@freezed
class CounterMsg extends Msg<CounterModel> with _$CounterMsg {
const factory CounterMsg.increment(int amount) = IncrementMsg;
const factory CounterMsg.decrement(int amount) = DecrementMsg;
}
class UpdateCounter extends Update<CounterModel, CounterMsg> {
@override
ProducedState<CounterModel> update(CounterMsg message, CounterModel model) =>
message.map(
increment: (msg) => ProducedState(
model.copyWith(currentValue: model.currentValue + msg.amount),
),
decrement: (msg) => ProducedState(
model.copyWith(currentValue: model.currentValue - msg.amount),
),
);
}
class CounterView extends View<CounterModel, CounterMsg> {
@override
Widget view(BuildContext context, CounterModel model) => Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Counter value: ${model.currentValue}'),
ElevatedButton(
onPressed: dispatchCallback(IncrementMsg(10)),
child: Text("Increment"),
),
ElevatedButton(
onPressed: dispatchCallback(DecrementMsg(1)),
child: Text("Decrement"),
),
],
),
),
);
}
final counterProgram = () => Program(
model: CounterModel(0),
view: () => CounterView(),
update: UpdateCounter(),
);
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'MVU Demo',
home: counterProgram(),
);
}
}
void main() => runApp(MyApp());