flutter-provider学习笔记

简介: flutter-provider学习笔记
1. InheritedWidget
  abstract class InheritedWidget extends ProxyWidget {
  
  const InheritedWidget({ Key? key, required Widget child })
    : super(key: key, child: child);

  @override
  InheritedElement createElement() => InheritedElement(this);
  
  @protected
  bool updateShouldNotify(covariant InheritedWidget oldWidget);
}
2. StatefulWidget
abstract class StatefulWidget extends Widget {
  
  const StatefulWidget({ Key? key }) : super(key: key);


  @override
  StatefulElement createElement() => StatefulElement(this);

 
  @protected
  @factory
  State createState(); // -> Widget build(BuildContext context);
}
3. StatelessWidget
 abstract class StatelessWidget extends Widget {
  
  const StatelessWidget({ Key? key }) : super(key: key);

 
  @override
  StatelessElement createElement() => StatelessElement(this);

 
  @protected
  Widget build(BuildContext context);
}
4.State
4.1 setState ->_element!.markNeedsBuild()
4.2 build-> Widget build(BuildContext context);
5.问题

5.1 为什么调用setState就会调用build?

因为调用markNeedsBuild方法标记element污染,需要在下一帧重建

5.2 到底是谁直接调用了build

?

5.3怎么判断是否需要更新Element

通过widget->canUpdate widget的类型和key

6.常用的类
abstract class InheritedContext<T> extends BuildContext {
    void markNeedsNotifyDependents();
}

abstract class Element extends DiagnosticableTree 
implements BuildContext {
 void didChangeDependencies();
 @protected  void performRebuild();
}

abstract class ComponentElement extends Element {
    Widget build();
}

abstract class ProxyElement extends ComponentElement {
    //关键 方法
   @protected void notifyClients(covariant ProxyWidget oldWidget);
}
class InheritedElement extends ProxyElement{}


class _InheritedProviderScopeElement<T> extends 
InheritedElement   implements InheritedContext<T> {}


class ChangeNotifierProvider<T extends ChangeNotifier?> extends ListenableProvider<T> {}


class ListenableProvider<T extends Listenable?> extends InheritedProvider<T>{}



class InheritedProvider<T> extends SingleChildStatelessWidget {
   @override
   Widget buildWithChild(BuildContext context, Widget? child);
   //构造方法中会实例该对象
   final _Delegate<T> _delegate;
}


class _InheritedProviderScope<T> extends InheritedWidget {
 @override
 _InheritedProviderScopeElement<T> createElement()
}

abstract class InheritedWidget extends ProxyWidget {}



class _CreateInheritedProviderState<T>  extends _DelegateState<T, _CreateInheritedProvider<T>>{
    /// 关键
    T? _value;
   
    T get value {}
}

class _CreateInheritedProvider<T> extends _Delegate<T> {
    ///delegate.create!(element!)
   final Create<T>? create;
}

abstract class _DelegateState<T, D extends _Delegate<T>> {
    
    _InheritedProviderScopeElement<T>? element;
}



class ChangeNotifier implements Listenable{
   notifyListeners()
}

6.1 继承关系

Widget

ProxyWidget

InheritedWidget

_InheritedProviderScope

StatelessWidget

SingleChildStatelessWidget

InheritedProvider


BuildContext

InheritedContext

Element

ComponentElement

ProxyElement

InheritedElement

_InheritedProviderScopeElement


_Delegate

_DelegateState

6.2 InheritedProvider

属性:(InheritedContext element, T value)-> StartListening

终于联系起来了value 就是ChangeNotifier 监听添加的就是markNeedsNotifyDependents方法,

notifyListeners->listener其实调用你的是markNeedsNotifyDependents

1.notifyListeners->listener->markNeedsNotifyDependents->markNeedsBuild-performRebuild->build->

notifyClients->notifyDependent->didChangeDependencies->markNeedsBuild

    ///该方法是在get value的时候调用的
  ///ListenableProvider
static VoidCallback _startListening(
    InheritedContext e,
    Listenable? value,
  ) {
    value?.addListener(e.markNeedsNotifyDependents);
    return () => value?.removeListener(e.markNeedsNotifyDependents);
  }
  
  ///_CreateInheritedProviderState
  @override
  T get value {
    if (_didInitValue && _value is! T) {
      throw StateError(
        'Tried to read a provider that threw during the creation of its value.\n'
        'The exception occurred during the creation of type $T.',
      );
    }
    if (!_didInitValue) {
      _didInitValue = true;
      if (delegate.create != null) {
        try {
          _value = delegate.create!(element!);
        } finally {
        }
      }
      if (delegate.update != null) {
        try {
          _value = delegate.update!(element!, _value);
        } finally {
        }
      }
    }
    element!._isNotifyDependentsEnabled = false;
    _removeListener ??= delegate.startListening?.call(element!, _value as T);
    element!._isNotifyDependentsEnabled = true;
    return _value as T;
  }
  
  
  ///_InheritedProviderScopeElement
  ///

   @override
  void performRebuild() {
    if (_firstBuild) {
      _firstBuild = false;
      _delegateState = widget.owner._delegate.createState()..element = this;
    }
    super.performRebuild();
  }
  
  ///InheritedElement
   @override
  void notifyClients(InheritedWidget oldWidget) {
    for (final Element dependent in _dependents.keys) {
      notifyDependent(oldWidget, dependent);
    }
  }
}
 ///Element
  @mustCallSuper
  void didChangeDependencies() {
    markNeedsBuild();
  }

///ComponentElement
@override
  void performRebuild() {
    Widget? built;
    try {
      built = build();
    } catch (e, stack) {
      built = ErrorWidget.builder(),
    } finally {
      _dirty = false;
    }
    try {
      _child = updateChild(_child, built, slot);
    } catch (e, stack) {
      built = ErrorWidget.builder();
      _child = updateChild(null, built, slot);
    }
  }
  
  ///_InheritedProviderScopeElement
  @override
  void markNeedsNotifyDependents() {
    if (!_isNotifyDependentsEnabled) {
      return;
    }
    markNeedsBuild();
    _shouldNotifyDependents = true;
  }
  
    ///_InheritedProviderScopeElement
   @override
    Widget build() {
    if (widget.owner._lazy == false) {
      value; // this will force the value to be computed.
    }
    _delegateState.build(
      isBuildFromExternalSources: _isBuildFromExternalSources,
    );
    _isBuildFromExternalSources = false;
    if (_shouldNotifyDependents) {
      _shouldNotifyDependents = false;
      notifyClients(widget);
    }
    return super.build();
    } 
      
     ///InheritedProviderScopeElement
   @override
  void notifyDependent(InheritedWidget oldWidget, Element dependent) {
    final dependencies = getDependencies(dependent);

    if (kDebugMode) {
      ProviderBinding.debugInstance.providerDidChange(_debugId);
    }

    var shouldNotify = false;
    if (dependencies != null) {
      if (dependencies is _Dependency<T>) {
        if (dependent.dirty) {
          return;
        }
        for (final updateShouldNotify in dependencies.selectors) {
          try {
            shouldNotify = updateShouldNotify(value);
          } finally {
          }
          if (shouldNotify) {
            break;
          }
        }
      } else {
        shouldNotify = true;
      }
    }

    if (shouldNotify) {
      dependent.didChangeDependencies();
    }
  }
      
   ///InheritedProvider
   @override
  Widget buildWithChild(BuildContext context, Widget? child) {
    return _InheritedProviderScope<T>(
      owner: this,
      child: builder != null
          ? Builder(
              builder: (context) => builder!(context, child),
            )
          : child!,
    );
  }
}
///_InheritedProviderScope
 @override
  _InheritedProviderScopeElement<T> createElement() {
    return _InheritedProviderScopeElement<T>(this);
  }
  
  
  
  ///_CreateInheritedProvider
   @override
   _CreateInheritedProviderState<T> createState()               =>_CreateInheritedProviderState();
  

6.3 Provider.of

注册监听并获取ChangeNotifier

BuildContext->dependOnInheritedElement->InheritedElement->updateDependencies->setDependencies->添加到_dependents(需要监听的Map)中


///Provider
static T of<T>(BuildContext context, {bool listen = true}) {
  final inheritedElement = _inheritedElementOf<T>(context);

    if (listen) {
      context.dependOnInheritedElement(inheritedElement);
    }
    return inheritedElement.value;
}

 static _InheritedProviderScopeElement<T> _inheritedElementOf<T>(
    BuildContext context,
  ) {
  ///context.getElementForInheritedWidgetOfExactType()
  }
  
  ///Element
   @override
  InheritedElement? getElementForInheritedWidgetOfExactType<T extends InheritedWidget>() {
    assert(_debugCheckStateIsActiveForAncestorLookup());
    final InheritedElement? ancestor = _inheritedWidgets == null ? null : _inheritedWidgets![T];
    return ancestor;
  }
  
    ///一级一级的赋值给子节点Element的 _inheritedWidgets 变量
    ///  mount和activate中调用_updateInheritance方法
  @override
  void _updateInheritance() {
    final Map<Type, InheritedElement>? incomingWidgets = _parent?._inheritedWidgets;
    if (incomingWidgets != null)
      _inheritedWidgets = HashMap<Type, InheritedElement>.from(incomingWidgets);
    else
      _inheritedWidgets = HashMap<Type, InheritedElement>();
      _inheritedWidgets![widget.runtimeType] = this;
  }


///  
///notifyClients中遍历
final Map<Element, Object?> _dependents
///
Set<InheritedElement>? _dependencies;

///BuildContext
 @override
 InheritedWidget dependOnInheritedElement(InheritedElement ancestor, { Object? aspect }) {
    assert(ancestor != null);
    _dependencies ??= HashSet<InheritedElement>();
    _dependencies!.add(ancestor);
    ancestor.updateDependencies(this, aspect);
    return ancestor.widget;
  }

 
7.Selector Consumer Builder
  
   class Builder extends StatelessWidget {
      final WidgetBuilder builder;
     @override
     Widget build(BuildContext context) => builder(context);
    }
    
    
    class Consumer<T> extends SingleChildStatelessWidget {
      @override
      Widget buildWithChild(BuildContext context, Widget? child) {
      return builder(
        context,
        Provider.of<T>(context),
        child,
      );
     }
  }
    
    
    
    class Selector0<T> extends SingleChildStatefulWidget {
        
         @override
           _Selector0State<T> createState() => _Selector0State<T>();
      
      }
 class _Selector0State<T> extends SingleChildState<Selector0<T>> {
            @override 
            Widget buildWithChild(BuildContext context, Widget? child) {
                    if (shouldInvalidateCache) {
                      value = selected;
                      oldWidget = widget;
                      cache = widget.builder(
                        context,
                        selected,
                        child,
                      );
                    }
                    return cache!;
            }

    }
    
    class Selector<A, S> extends Selector0<S> {
  Selector({
    Key? key,
    required ValueWidgetBuilder<S> builder,
    required S Function(BuildContext, A) selector,
    ShouldRebuild<S>? shouldRebuild,
    Widget? child,
  }) : super(
          key: key,
          shouldRebuild: shouldRebuild,
          builder: builder,
          selector: (context) => selector(context, Provider.of(context)),
          child: child,
        );
}


参考资料
相关文章
|
6月前
|
设计模式 缓存 Dart
Flutter学习笔记&学习资料推荐,15分钟的字节跳动视频面试
Flutter学习笔记&学习资料推荐,15分钟的字节跳动视频面试
|
Android开发 容器
[译]Flutter学习笔记:BottomNavigationBar实现多个Navigation
这个文章解决了什么问题? 最近我研究了一下Flutter,但是在使用Navigator的时候遇到了一个很头痛的问题,就是当我们去来回切换导航按钮时,Flutter会重新build,从而导致控件重新Build,从而会失去浏览历史。
1810 0
|
1月前
|
Android开发 iOS开发 容器
鸿蒙harmonyos next flutter混合开发之开发FFI plugin
鸿蒙harmonyos next flutter混合开发之开发FFI plugin
|
5月前
|
开发框架 前端开发 测试技术
Flutter开发常见问题解答
Flutter开发常见问题解答
|
1月前
|
开发者
鸿蒙Flutter实战:07-混合开发
鸿蒙Flutter混合开发支持两种模式:1) 基于har包,便于主项目开发者无需关心Flutter细节,但不支持热重载;2) 基于源码依赖,利于代码维护与热重载,需配置Flutter环境。项目结构包括AppScope、flutter_module等目录,适用于不同开发需求。
74 3
|
16天前
|
传感器 开发框架 物联网
鸿蒙next选择 Flutter 开发跨平台应用的原因
鸿蒙(HarmonyOS)是华为推出的一款旨在实现多设备无缝连接的操作系统。为了实现这一目标,鸿蒙选择了 Flutter 作为主要的跨平台应用开发框架。Flutter 的跨平台能力、高性能、丰富的生态支持和与鸿蒙系统的良好兼容性,使其成为理想的选择。通过 Flutter,开发者可以高效地构建和部署多平台应用,推动鸿蒙生态的快速发展。
128 0
|
18天前
|
Dart 安全 UED
Flutter&鸿蒙next中的表单封装:提升开发效率与用户体验
在移动应用开发中,表单是用户与应用交互的重要界面。本文介绍了如何在Flutter中封装表单,以提升开发效率和用户体验。通过代码复用、集中管理和一致性的优势,封装表单组件可以简化开发流程。文章详细讲解了Flutter表单的基础、封装方法和表单验证技巧,帮助开发者构建健壮且用户友好的应用。
58 0
|
1月前
|
开发框架 移动开发 Android开发
安卓与iOS开发中的跨平台解决方案:Flutter入门
【9月更文挑战第30天】在移动应用开发的广阔舞台上,安卓和iOS两大操作系统各自占据半壁江山。开发者们常常面临着选择:是专注于单一平台深耕细作,还是寻找一种能够横跨两大系统的开发方案?Flutter,作为一种新兴的跨平台UI工具包,正以其现代、响应式的特点赢得开发者的青睐。本文将带你一探究竟,从Flutter的基础概念到实战应用,深入浅出地介绍这一技术的魅力所在。
77 7
|
1月前
|
编解码 Dart API
鸿蒙Flutter实战:06-使用ArkTs开发Flutter鸿蒙插件
本文介绍了如何开发一个 Flutter 鸿蒙插件,实现 Flutter 与鸿蒙的混合开发及双端消息通信。通过定义 `MethodChannel` 实现 Flutter 侧的 token 存取方法,并在鸿蒙侧编写 `EntryAbility` 和 `ForestPlugin`,使用鸿蒙的首选项 API 完成数据的读写操作。文章还提供了注意事项和参考资料,帮助开发者更好地理解和实现这一过程。
56 0
|
1月前
|
Dart Android开发
鸿蒙Flutter实战:03-鸿蒙Flutter开发中集成Webview
本文介绍了在OpenHarmony平台上集成WebView的两种方法:一是使用第三方库`flutter_inappwebview`,通过配置pubspec.lock文件实现;二是编写原生ArkTS代码,自定义PlatformView,涉及创建入口能力、注册视图工厂、处理方法调用及页面构建等步骤。
48 0