melodysdreamj / june

MIT License
50 stars 4 forks source link

Is there a way to access to the build context from state class? #5

Closed mkaramuk closed 1 month ago

mkaramuk commented 5 months ago

I put the event handlers of the widgets (such as buttons) to inside the state class. Sometimes, such as when routing to another path, I need to access BuildContext. Currently I solved it by passing context to the handler function. Wouldn't it be better if June provides access to the build context by default?

My current approach is like this:

class WelcomeScreenVM extends JuneState {
  int selectedPage = 0;

  // Methods
  bool isLastPage() {
    return selectedPage == WELCOME_PAGES.length - 1;
  }

  void changePage(int index) {
    selectedPage = index;
    setState();
  }

  // Events
  void onForwardClick(BuildContext context) {
    if (!isLastPage()) {
      changePage(++selectedPage);
      setState();
    } else {
      context.go("/dashboard");
    }
  }
}

The widget:


  @override
  Widget build(BuildContext context) {
    return JuneBuilder(() => WelcomeScreenVM(),
        builder: (vm) =>  IconButton(
            onPressed: () => vm.onForwardClick(context),
            icon: Icon(vm.isLastPage()
                ? Icons.check
                : Icons.arrow_forward));
  }
CodingWill0 commented 2 months ago

As far as I understand, June is aiming to 'feel' like vanilla Flutter, and in vanilla Flutter it's pretty normal to send the context as parameter around the code. So I'd say your approach is the expected one.

melodysdreamj commented 1 month ago

@CodingWill0, thank you for explaining it so well! You've perfectly captured the intention behind the design, and I really appreciate your clear explanation. It's been very helpful! 😊