定义的数据模型为
import 'package:flutter/material.dart';
import 'user_type.dart';
class UserInheritedModel extends InheritedModel<UserType> {
final int age;
final int weight;
const UserInheritedModel(
{required this.age, required this.weight, required Widget child})
: super(child: child);
static UserInheritedModel? of(BuildContext context,
{required UserType aspect}) {
return InheritedModel.inheritFrom<UserInheritedModel>(context,
aspect: aspect);
}
@override
bool updateShouldNotify(UserInheritedModel old) {
return age != old.age || weight != old.weight;
}
@override
bool updateShouldNotifyDependent(
UserInheritedModel old, Set<UserType> aspects) {
return (aspects.contains(UserType.age) && age != old.age) ||
(aspects.contains(UserType.height) && weight != old.weight);
}
}
要局部刷新的页面为
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
InkWell(
child: const AgePage(
ideaType: UserType.age,
),
onTap: () {
setState(() {
_age += 1;
});
},
),
Divider(),
InkWell(
child: const WeightPage(
ideaType: UserType.height,
),
onTap: () {
setState(() {
_weight += 1;
});
},
),
],
),
包含的页面为
class AgePage extends StatelessWidget {
final UserType ideaType;
const AgePage({Key? key, required this.ideaType}) : super(key: key);
@override
Widget build(BuildContext context) {
final UserInheritedModel? _ideasTypeIdea =
UserInheritedModel.of(context, aspect: ideaType);
return Text(
'${_ideasTypeIdea!.age}\n${Random.secure().nextDouble()}',
);
}
}
另一个页面与上面的类似