另一个MVC例子, 此处加上Controller。
main.dart
import 'package:flutter/material.dart';
import 'view/counter_page.dart';
void main(List<String> args) {
runApp(
const MaterialApp(
home: CounterPage(),
),
);
}
controller/counter_controller.dart
import '../model/counter_model.dart';
class CounterController {
final CounterModel _m = CounterModel();
void increase() {
_m.increase();
}
void decrease() {
_m.decrease();
}
CounterModel get listener => _m;
}
model/counter_model.dart
import 'package:flutter/material.dart';
class CounterModel with ChangeNotifier {
int _count = 0;
int get count => _count;
void increase() {
_count++;
notifyListeners();
}
void decrease() {
_count--;
notifyListeners();
}
}
view/counter_view.dart
import 'package:flutter/material.dart';
import '../controller/counter_controller.dart';
class CounterPage extends StatefulWidget {
const CounterPage({super.key});
@override
State<CounterPage> createState() => _CounterPageState();
}
class _CounterPageState extends State<CounterPage> {
CounterController c = CounterController();
@override
Widget build(BuildContext context) {
return Scaffold(
body: Align(
alignment: Alignment.center,
child: Container(
constraints: const BoxConstraints.expand(),
color: Colors.grey,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ListenableBuilder(
listenable: c.listener,
builder: (context, child) {
return Text("${c.listener.count}");
},
)
],
),
),
),
floatingActionButton: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
FloatingActionButton(
onPressed: c.increase,
child: const Icon(Icons.add),
),
FloatingActionButton(
onPressed: c.decrease,
child: const Icon(Icons.approval_rounded),
),
],
),
);
}
}