skip to Main Content

I have a page, a widget an a provider.

The page has some elements in it but there is a widget that I need to use for other pages so that’s why it’s separated into another widget. This widget is just a dialog, so it’s a class without any state:

class Difficulty {

  showModal() {
    var settingsController = context.watch<SettingsController>(); // this is what I'd need

    return showPlatformDialog(
    ...

So in my page, I call Difficulty().showPlatformDialog(), but I’d need the context from previous page or create a new one.

What’s the best approach?

  1. Pass it to Difficulty()
  2. Pass it to showModal()
  3. Create a StatefulBuilder or something else with its own context

2

Answers


  1. You just need to pass the BuildContext as a parameter to showPlatformDialog().

    Example:

    class Difficulty {
    
      showModal(BuildContext context) {
        var settingsController = context.watch<SettingsController>(); // this is what I'd need
    
        return showPlatformDialog(
                                    ....
    

    And call the function from the widget as

    Difficulty().showPlatformDialog(context)
    

    To answer your query, You can pass the context in any way like passing it to the function or creating a stateless/stateful widget.

    I prefer the third approach though

    Login or Signup to reply.
  2. Or you can use the global level navigation key that you can use context anywhere on the project and you don’t have to pass the context.

    You can checkout the my answer here I explained there how to use it.

    https://stackoverflow.com/a/71922909/10936691

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search