一、前言
在Flutter中有时候需要监听数据改变,在这里可以使用ChangeNotifier进行监听
二、演示代码
首先定义一个继承ChangeNotifier的数据类,代码如下:
Counter.dart
class Counter extends ChangeNotifier{//这里也可以使用with来进行实现
int _count = 0;//数值计算
int get count => _count;
addCount(){
_count++;
notifyListeners();
}
}
使用方式如下:
Counter _counter = new Counter();
_counter.addListener(() {
//数值改变的监听
print('YM------>新数值:${_counter.count}');
});
完整代码如下:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class Counter extends ChangeNotifier{
int _count = 0;//数值计算
int get count => _count;
addCount(){
_count++;
notifyListeners();
}
}
Counter _counter = new Counter();
class MyApp extends StatefulWidget {
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
void initState() {
super.initState();
_counter.addListener(() {
//数值改变的监听
print('YM------>新数值:${_counter.count}');
});
}
void dispose() {
super.dispose();
_counter.dispose();//移除监听
}
Widget build(BuildContext context) {
return MaterialApp(
title: 'Material App',
home: Scaffold(
appBar: AppBar(
title: Text('Material App Bar'),
),
body: Center(
child: Container(
child: RaisedButton(
onPressed: (){
_counter.addCount();
},
child: Text('计数')
),
),
),
),
);
}
}
三、总结
ChangeNotifier也有其延伸的子类ValueNotifier,来对一些基本类型进行处理,关于这个可以参考以下链接:
本文介绍了如何在Flutter中使用ChangeNotifier监听数据变化,通过Counter示例展示了如何创建和使用,并提到了ValueNotifier的延伸。

1841

被折叠的 条评论
为什么被折叠?



