Context lifting
The age old problem of propagating state through the tree is that Navigator is a single central widget that hosts all routes.
When one pushes a new route, is it not a child of the current widget, but rather a child of the Navigator, and inherits it's context, rather than the one we were just in. This causes a common misconception in what is available in the current context.
While it is possible to solve this problem by using a complex nested Routing system like [Beamer](https://pub.dev/packages/beamer), in vanilla flutter and most other routers, this issue persists.
It can also be solved by explicitly re-injecting anything we want in the context. For example, a context_plus Ref:
```dart
final MyRef = Ref<String>();
class Home extends StatelessWidget {
const Home({super.key});
@override
Widget build(BuildContext context) {
MyRef.bind(context, () => 'Hello World!');
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text('Context Lifting'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(MyRef.of(context)),
ElevatedButton(
onPressed:
() => showDialog(
context: context,
builder: (dialogContext) {
MyRef.bindValue(dialogContext, MyRef.of(context));
return const MyDialog();
},
),
child: const Text('Show Dialog'),
),
],
),
),
);
}
}
```
However, the other day I have seen a package with a potentially even more elegant solution:
In the [Disco](https://pub.dev/packages/disco) package, a Widget called [`ProviderScopePortal`](https://disco.mariuti.com/core/modals/) automatically reinjects all Providers found in the context. The source code for this Widget can be found [here](https://github.com/our-creativity/disco/blob/88edcddc7c983789d4e0b9e32bede86b8bddcf7e/packages/disco/lib/src/widgets/provider_scope_portal.dart). It most likely requires a very specific Setup to work (like being able to extract all Providers found in the current context).
But it seemed interesting to me so I wanted to mention it here, in case such a utility would be beneficial and possible in this package.
关闭于 2025-05-27 2 条评论