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,
        );
}


参考资料
相关文章
|
5月前
|
设计模式 缓存 Dart
Flutter学习笔记&学习资料推荐,15分钟的字节跳动视频面试
Flutter学习笔记&学习资料推荐,15分钟的字节跳动视频面试
|
Android开发 容器
[译]Flutter学习笔记:BottomNavigationBar实现多个Navigation
这个文章解决了什么问题? 最近我研究了一下Flutter,但是在使用Navigator的时候遇到了一个很头痛的问题,就是当我们去来回切换导航按钮时,Flutter会重新build,从而导致控件重新Build,从而会失去浏览历史。
1797 0
|
4月前
|
开发框架 前端开发 测试技术
Flutter开发常见问题解答
Flutter开发常见问题解答
|
4天前
|
开发框架 移动开发 Android开发
安卓与iOS开发中的跨平台解决方案:Flutter入门
【9月更文挑战第30天】在移动应用开发的广阔舞台上,安卓和iOS两大操作系统各自占据半壁江山。开发者们常常面临着选择:是专注于单一平台深耕细作,还是寻找一种能够横跨两大系统的开发方案?Flutter,作为一种新兴的跨平台UI工具包,正以其现代、响应式的特点赢得开发者的青睐。本文将带你一探究竟,从Flutter的基础概念到实战应用,深入浅出地介绍这一技术的魅力所在。
19 7
|
5月前
|
前端开发 C++ 容器
Flutter-完整开发实战详解(一、Dart-语言和-Flutter-基础)(1)
Flutter-完整开发实战详解(一、Dart-语言和-Flutter-基础)(1)
|
22天前
|
JSON Dart Java
flutter开发多端平台应用的探索
flutter开发多端平台应用的探索
27 6
|
22天前
|
JSON Dart Java
flutter开发多端平台应用的探索 下 (跨模块、跨语言通信之平台通道)
flutter开发多端平台应用的探索 下 (跨模块、跨语言通信之平台通道)
|
25天前
|
安全 Android开发 开发者
探索安卓开发的未来:Kotlin的崛起与Flutter的挑战
在移动开发的广阔天地中,安卓平台始终占据着举足轻重的地位。随着技术的不断进步和开发者需求的多样化,Kotlin和Flutter成为了改变游戏规则的新玩家。本文将深入探讨Kotlin如何以其现代化的特性赢得开发者的青睐,以及Flutter凭借跨平台的能力如何挑战传统的安卓开发模式。通过实际案例分析,我们将揭示这两种技术如何塑造未来的安卓应用开发。
52 6
|
2月前
|
开发框架 Android开发 iOS开发
Flutter相关痛点解决问题之淘特选择桌面端开发框架如何解决
Flutter相关痛点解决问题之淘特选择桌面端开发框架如何解决
|
2月前
|
移动开发 前端开发 JavaScript
"跨界大战!React Native、Weex、Flutter:三大混合开发王者正面交锋,揭秘谁才是你移动应用开发的终极利器?"
【8月更文挑战第12天】随着移动应用开发的需求日益增长,高效构建跨平台应用成为关键。React Native、Weex与Flutter作为主流混合开发框架各具特色。React Native依托Facebook的强大支持,以接近原生的性能和丰富的组件库著称;Weex由阿里巴巴开发,性能优越尤其在大数据处理上表现突出;Flutter则凭借Google的支持及独特的Dart语言和Skia渲染引擎,提供出色的定制能力和开发效率。选择时需考量项目特性、团队技能及生态系统的成熟度。希望本文对比能助你做出最佳决策。
122 1
下一篇
无影云桌面