createContext<TValue> function
Context<TValue?>
createContext<TValue>([
- TValue? defaultValue,
- int calculateChangedBits(
- TValue?,
- TValue?
Creates a Context object.
When React renders a component that subscribes to this Context object it will read the current context value from the closest matching Provider above it in the tree.
To create a context with a non-nullable generic type, use createContextInit instead (caveat: requires a default value).
Example:
final MyContext = createContext<String?>();
example() {
return Fragment()(
(MyContext.Provider()..value = 'new context value')(
// Consume using either a function component, class component, or Context.Consumer utility.
// Each of the following children renders a span with 'new context value'.
ExampleFunctionConsumer()(),
ExampleClassConsumer()(),
MyContext.Consumer()(
(value) => Dom.span()(value),
),
),
// When not nested in a matching Provider, the default value (null) is used.
// To provide a default value, use createContextInit instead of createContext.
ExampleFunctionConsumer()(), // Renders an empty span.
);
}
mixin ExampleFunctionConsumerProps on UiProps {}
UiFactory<ExampleFunctionConsumerProps> ExampleFunctionConsumer = uiFunction((props) {
final contextValue = useContext(MyContext);
return Dom.span()(contextValue);
}, _$ExampleFunctionConsumerConfig);
UiFactory<ExampleClassConsumerProps> ExampleClassConsumer = castUiFactory(_$ExampleClassConsumer);
mixin ExampleClassConsumerProps on UiProps {}
class ExampleClassConsumerComponent extends UiComponent2<ExampleClassConsumerProps> {
@override
get contextType => MyContext.reactDartContext;
render() {
return Dom.span()(this.context);
}
Learn more: react.dev/reference/react/createContext
Implementation
Context<TValue?> createContext<TValue>([
// TODO(FED-2136) uncomment this deprecation
// @Deprecated('Use `createContextInit` instead to create contexts with initial values.'
// ' Since the argument to createContextInit is required, it can be used to create a context that holds a non-nullable type,'
// ' whereas this function can only create contexts with nullable type arguments.')
TValue? defaultValue,
int Function(TValue?, TValue?)? calculateChangedBits,
]) => createContextInit(defaultValue, calculateChangedBits);