Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ancestorInheritedElementForWidgetOfExactType is deprecated

Tags:

flutter

dart

After Flutter version 1.12.1 ancestorInheritedElementForWidgetOfExactType is deprecated. We should use getElementForInheritedWidgetOfExactType now. How do I edit this BlocProvider to work with this new method?

import 'package:flutter/material.dart';

Type _typeOf<T>() => T;

abstract class BlocBase {
  void dispose();
}

class BlocProvider<T extends BlocBase> extends StatefulWidget {
  BlocProvider({
    Key key,
    @required this.child,
    @required this.bloc,
  }) : super(key: key);
  final Widget child;
  final T bloc;

  @override
  _BlocProviderState<T> createState() => _BlocProviderState<T>();

  static T of<T extends BlocBase>(BuildContext context) {
    final type = _typeOf<_BlocProviderInherited<T>>();
    _BlocProviderInherited<T> provider =
        context.ancestorInheritedElementForWidgetOfExactType(type)?.widget; //deprecated
    return provider?.bloc;
  }
}

class _BlocProviderState<T extends BlocBase> extends State<BlocProvider<T>> {
  @override
  void dispose() {
    widget.bloc?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return new _BlocProviderInherited<T>(
      bloc: widget.bloc,
      child: widget.child,
    );
  }
}

class _BlocProviderInherited<T> extends InheritedWidget {
  _BlocProviderInherited({
    Key key,
    @required Widget child,
    @required this.bloc,
  }) : super(key: key, child: child);
  final T bloc;

  @override
  bool updateShouldNotify(_BlocProviderInherited oldWidget) => false;
} 

Do I get rid of the _typeOf variable now? What are the benefits of this change?

like image 684
PoQ Avatar asked Dec 25 '19 23:12

PoQ


1 Answers

Use context.getElementForInheritedWidgetOfExactType<_BlocProviderInherited<T>>().widget and it should work.

As far as benefits go, the documentation basically states the same though someone can correct me but I don't see any difference. You should be able to get rid of the _typeOf variable.

like image 54
Benjamin Avatar answered Nov 15 '22 11:11

Benjamin