Access Flutter provider from another provider? #51
-
I'm very interested in this method of state management so far and I'd like to use it in my projects going forward but I can't seem to find the correct way to access a provider from within a provider using the Flutter version of this package. For example (using the Todo example structure as a base), let's say I have 2 providers:
How would I access the current value (or even listen to) the Would I have one controller that contains both the |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
Given the following controllers: class UserController {
final _user = createSignal<User?>(null);
// Expose the read-only signal
late final user = _user.toReadSignal();
}
class PostsController {
PostsController({
required this.user,
});
final ReadSignal<User?> user;
final posts = createSignal<List<Post>>([]);
} The class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return Solid(
providers: [
SolidProvider<UserController>(create: () => UserController())
],
child: MaterialApp(...),
);
}
} And below we may have: class PostsPage extends StatelessWidget {
const PostsPage({super.key});
@override
Widget build(BuildContext context) {
return Solid(
providers: [
SolidProvider<PostsController>(
create: () => PostsController(
user: context.get<UserController>().user,
),
),
],
child: const Placeholder(),
);
}
} Put in simple words, shared providers need to be at the top of the tree so children can access their values. |
Beta Was this translation helpful? Give feedback.
-
Ah, I see, so the way to do this would be inject as the lowest possible point in the tree, or at least lower than the dependencies. So if I were to make this a little more complex and add some additional providers I needed to access "globally" that are dependent on other providers, I would do the following, correct? class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return Solid(
providers: [
SolidProvider<UserController>(create: () => UserController()),
SolidProvider<OtherController>(create: () => OtherController()),
],
child: Solid(
providers: [
SolidProvider<DependantController1>(create: () => DependantController1(
user: context.get<UserController>().user,
)),
SolidProvider<DependantController2>(create: () => DependantController2(
user: context.get<UserController>().user,
otherController: context.get<OtherController>(),
)),
],
child: MaterialApp(...)
);
);
}
} |
Beta Was this translation helpful? Give feedback.
Given the following controllers:
The
PostsController
depends on theuser
signal.At the start of the tree we may have:
A…