Creating a Holder or Context in Flutter

Tiempo de lectura: 2 minutos

En Flutter there is no React Hooks (like react native), but it has a widget tree where you can inject data from top to bottom.

Autumn -pexels

It is the pure equivalent of React Context, although at a lower level.

BASIC EXAMPLE:

import 'package:flutter/material.dart'; class CounterHolder extends InheritedWidget { final int counter; final Function() increment; const CounterHolder({ Key? key, required this.counter, required this.increment, required Widget child, }) : super(key: key, child: child); static CounterHolder of(BuildContext context) { return context.dependOnInheritedWidgetOfExactType()!; } @override bool updateShouldNotify(CounterHolder oldWidget) { return counter != oldWidget.counter; } } class CounterApp extends StatefulWidget { const CounterApp({super.key}); @override State createState() => _CounterAppState(); } class _CounterAppState extends State { int counter = 0; void increment() { setState(() => counter++); } @override Widget build(BuildContext context) { return CounterHolder( counter: counter, increment: increment, child: Scaffold( appBar: AppBar(title: const Text('Counter Holder')), body: Center(child: Text('Valor: $counter')), floatingActionButton: FloatingActionButton( onPressed: CounterHolder.of(context).increment, child: const Icon(Icons.add), ), ), ); } } 

This is the most similar to a Context.Provider and useContext in React.

MODERN STANDARD:

This is the most modern and similar to “Context + Hooks” of React.

# pubspec.yaml dependencies: flutter: sdk: flutter provider: ^6.1.2 

Example:

import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; class CounterModel with ChangeNotifier { int _count = 0; int get count => _count; void increment() { _count++; notifyListeners(); } } void main() { runApp( ChangeNotifierProvider( create: (_) => CounterModel(), child: const MyApp(), ), ); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: const Text("Provider Example")), body: Center( child: Text( 'Count: ${context.watch().count}', style: const TextStyle(fontSize: 30), ), ), floatingActionButton: FloatingActionButton( onPressed: () => context.read().increment(), child: const Icon(Icons.add), ), ), ); } } 

🔹 ChangeNotifierProvider → is like your “Context Provider”.
🔹 context.watch<T>() → is like useContext() that listens for changes.
🔹 context.read<T>() → accesses the value without listening for changes (like a useRef or dispatch).

If you were using something like Redux or Zustand in React, in Flutter you can use:

Leave a Comment