Flutter使用InheritedModel实现局部刷新

Flutter使用InheritedModel实现局部刷新,第1张

Flutter使用InheritedModel实现局部刷新

定义的数据模型为

import 'package:flutter/material.dart';
import 'user_type.dart';

class UserInheritedModel extends InheritedModel {
  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(context,
        aspect: aspect);
  }

  @override
  bool updateShouldNotify(UserInheritedModel old) {
    return age != old.age || weight != old.weight;
  }

  @override
  bool updateShouldNotifyDependent(
      UserInheritedModel old, Set aspects) {
    return (aspects.contains(UserType.age) && age != old.age) ||
        (aspects.contains(UserType.height) && weight != old.weight);
  }
}

要局部刷新页面

Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              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()}',
    );
  }
}

另一个页面与上面的类似

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5683945.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存