如何将 Flutter 钩子与 ChangeNotifer 结合使用
How to use Flutter hooks with ChangeNotifer
假设我们有一个带有 ChangeNotifer
的复杂模型,那么我应该如何在模型更改时自动更新 UI?
这是我想出来的,但看起来很奇怪,对吗,有更好的方法吗?
class Playground extends HookWidget {
const Playground({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
print("built");
final dataState = useState(DataClass(0));
final data = useListenable(dataState.value);
return Scaffold(
appBar: AppBar(
title: Text('Title'),
),
body: ListView(
children: [
ListTile(
title: Text("data: ${data.cnt}"),
onTap: () {
data.cnt++;
},
),
],
),
);
}
}
class DataClass with ChangeNotifier {
int _cnt;
int get cnt => _cnt;
set cnt(int val) {
_cnt = val;
notifyListeners();
}
DataClass(int cnt) : _cnt = cnt;
}
ps:类似于 useStateListenable
或 useListenableProvider
您可以将 useState
和 useListenable
组合成 useListenableState
T useListenableState<T extends ChangeNotifier>(T data) {
final state = useState<T>(data);
return useListenable(state.value);
}
class Playground extends HookWidget {
const Playground({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
print("built");
final data = useListenableState(DataClass(0));
return Scaffold(
appBar: AppBar(
title: Text('Title'),
),
body: ListView(
children: [
ListTile(
title: Text("data: ${data.cnt}"),
onTap: () {
data.cnt++;
},
),
],
),
);
}
}
class DataClass with ChangeNotifier {
int _cnt;
int get cnt => _cnt;
set cnt(int val) {
_cnt = val;
notifyListeners();
}
DataClass(int cnt) : _cnt = cnt;
}
假设我们有一个带有 ChangeNotifer
的复杂模型,那么我应该如何在模型更改时自动更新 UI?
这是我想出来的,但看起来很奇怪,对吗,有更好的方法吗?
class Playground extends HookWidget {
const Playground({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
print("built");
final dataState = useState(DataClass(0));
final data = useListenable(dataState.value);
return Scaffold(
appBar: AppBar(
title: Text('Title'),
),
body: ListView(
children: [
ListTile(
title: Text("data: ${data.cnt}"),
onTap: () {
data.cnt++;
},
),
],
),
);
}
}
class DataClass with ChangeNotifier {
int _cnt;
int get cnt => _cnt;
set cnt(int val) {
_cnt = val;
notifyListeners();
}
DataClass(int cnt) : _cnt = cnt;
}
ps:类似于 useStateListenable
或 useListenableProvider
您可以将 useState
和 useListenable
组合成 useListenableState
T useListenableState<T extends ChangeNotifier>(T data) {
final state = useState<T>(data);
return useListenable(state.value);
}
class Playground extends HookWidget {
const Playground({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
print("built");
final data = useListenableState(DataClass(0));
return Scaffold(
appBar: AppBar(
title: Text('Title'),
),
body: ListView(
children: [
ListTile(
title: Text("data: ${data.cnt}"),
onTap: () {
data.cnt++;
},
),
],
),
);
}
}
class DataClass with ChangeNotifier {
int _cnt;
int get cnt => _cnt;
set cnt(int val) {
_cnt = val;
notifyListeners();
}
DataClass(int cnt) : _cnt = cnt;
}