EnvironmentKey<T, K extends EnvironmentKey<T, K>> class abstract base

A key for accessing and modifying associated values from the BuildContext.

EnvironmentKeys are an alternative to using InheritedWidgets for passing values down the widget tree.

An EnvironmentKey is less verbose to define than an InheritedWidget since it inherits the of and maybeOf methods instead of having to define the equivalent static accessors.

It further incorporates the concept of a defaultValue which is used when no value is provided through the BuildContext.

Example

The following example shows how to define a EnvironmentKey, as well as a extension method that is typically provided to make it easier to use.

import 'package:flutter/widgets.dart';

final class _DefaultPaddingKey
    extends EnvironmentKey<double, _DefaultPaddingKey> {
  const _DefaultPaddingKey();

  @override
  double defaultValue(BuildContext context) => 8;
}

const defaultPadding = _DefaultPaddingKey();

extension WidgetModifiers on Widget {
  @widgetFactory
  Widget defaultPadding(double amount) =>
      const _DefaultPaddingKey().update(value: amount, child: this);
}

To access the value of an EnvironmentKey from the BuildContext, use the of method:

Widget build(BuildContext context) {
  return Padding(
    padding: EdgeInsets.all(defaultPadding.of(context)),
    child: Container(),
  );
}
Available Extensions

Constructors

EnvironmentKey()
Constructor for subclasses.
const

Properties

hashCode int
The hash code for this object.
no setterinherited
runtimeType Type
A representation of the runtime type of the object.
no setterinherited

Methods

defaultValue(BuildContext context) → T
Returns the default value for this key, when no value is provided through the BuildContext.
maybeOf(BuildContext context) → T?
Returns the value of this key based on the given BuildContext or null if no value is provided.
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
of(BuildContext context) → T
Returns the value of this key form the given BuildContext or the defaultValue if no value is provided.
toString() String
A string representation of this object.
inherited

Operators

operator ==(Object other) bool
The equality operator.
inherited