ITADN

Make it possible to depend on sibling contexts.

#18Pull Requestarthurbcd 创建于 2024-12-15
A
arthurbcdcommented
#### **Description** This PR adds support for resolving providers from sibling routes or dialogs in a `ContextRefRoot`. It addresses a common limitation in `provider`, enabling providers to be read or watched across sibling contexts like sibling routes/dialogs. #### **The problem** The code below will throw '$ref is not bound`: ```dart final _counter = Ref<ValueNotifier<int>>(); class Example extends StatelessWidget { const Example({super.key}); @override Widget build(BuildContext context) { _counter.bind(context, () => ValueNotifier(0)); return CounterExample( onTap: () => showDialog( context: context, builder: (context) => AlertDialog( title: Text('Counter: ${_counter.watch(context)}'), // <-- Throws '$ref is not bound`. content: Text('Counter value: ${_counter.of(context).value++}'), // <-- Throws '$ref is not bound`. ), ), counter: _counter.watch(context), ); } } ``` #### **Code Changes** Added the following line to the provider resolution logic: ```dart if (provider == null) { bool visitDependent(Element element) { final p = ref.providers[element]; if (p != null) { provider = p; ref.dependentProvidersCache[context] = p; return false; } return true; } // Usually faster to visit ancestors first. context.visitAncestorElements(visitDependent); // With this, we can depend on siblings routes/dialogs. visitChildrenElements(visitDependent); } ``` #### **Impact** - This change resolves a major limitation of `provider`, allowing sibling routes or dialogs to read and watch providers seamlessly. - The lookup will resolve during the first frame and cache the result, ensuring the solution remains performant without introducing additional overhead. - This enhancement maintains compatibility with existing functionality while improving usability for complex navigation and dialog scenarios. I just want to say that I really admire your solutions and the thought process behind them. I’ve also come up with similar approaches in my own work, and it would be amazing if we could have a deeper discussion one day. I think we have similar goals and methodologies in mind—especially when looking at packages like `async_notifier` and `async_listenable`, which seem to tackle the same purpose. Perhaps we could collaborate in the future and work together instead of developing similar solutions independently. I believe we could create even more powerful tools by combining our efforts. Let me know what you think! 😊
合并状态:未合并 关闭于 2025-04-07 3 条评论