contexto 1.0.0
contexto: ^1.0.0 copied to clipboard
A simple and easy to shared data on Flutter.
Contexto #
A simple library to avoid prop drilling in Flutter using a context system similar to Context API from React.
โจ Features #
- Provision of status via
AppContext.provider
. - Easy access to status with
useContext<T>(context)
. - Dispatch function with
useDispatch<T>(context)
. - Automatic updates for dependent widgets.
๐ฆ Installation #
Add the dependency to your pubspec.yaml
:
dependencies:
contexto: ^1.0.0
Run the command to install the package:
dart pub get
๐ How to use #
Creating a Context Provider #
Wrap the widgets that need to access the state or value inside an AppContext.provider
.
import 'package:contexto/contexto.dart';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: AppContext.provider<int>(
value: 0,
child: CounterScreen(),
),
);
}
}
Accessing and updating values #
Use useContext<T>(context)
to access the state/value and useDispatch<T>(context)
to update it.
class CounterScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
final counter = useContext<int>(context);
final setCounter = useDispatch<int>(context);
return Scaffold(
appBar: AppBar(title: Text("Counter")),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("Value: \$counter", style: TextStyle(fontSize: 24)),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
IconButton(
onPressed: () => setCounter(counter - 1),
icon: Icon(Icons.remove),
),
IconButton(
onPressed: () => setCounter(counter + 1),
icon: Icon(Icons.add),
),
],
),
],
),
),
);
}
}
๐ API #
AppContext.provider<T>
#
A provider that makes a value available to descendant widgets without the need for prop drilling.
Parameters:
value
(T): Initial value.child
(Widget): The child widget that will access the value.
useContext<T>(context)
#
Returns the value of type T
from the nearest provider.
Use:
final value = useContext<MyType>(context);
useDispatch<T>(context)
#
Returns a function to update the value of type T
in the nearest provider.
Use:
final dispatch = useDispatch<int>(context);
dispatch(42); // Updates the state to 42
๐งช Tests #
To run the tests, execute the command:
dart test
๐ Contributing #
Contributions are welcome! Please submit pull requests with any improvements or bug fixes.
๐ License #
This project is licensed under the BSD 3 License - see the LICENSE file for details.