一个使用ChangeNotifier的MVC小示例
main.dart
import 'package:flutter/material.dart';
import 'view/counter_page.dart';
void main(List<String> args) {
runApp(
const MaterialApp(
home: CounterPage(),
),
);
}
model/couter_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_page.dart
import 'package:flutter/material.dart';
import '../model/counter_model.dart';
class CounterPage extends StatefulWidget {
const CounterPage({super.key});
@override
State<CounterPage> createState() => _CounterPageState();
}
class _CounterPageState extends State<CounterPage> {
CounterModel c = CounterModel();
@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,
builder: (context, child) {
return Text("${c.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),
),
],
),
);
}
}