Skip to content

StatefulWidget syntax in Flutter requires 2 classes #329

@ghost

Description

@iskakaushik commented on Apr 22, 2019, 8:22 PM UTC:

Currently when we create a StatefulWidget, we need to declare one class for the Widget and one class for the State. This issue is to explore ways in which we can do it with just one class.

Existing discussion:

@Hixie: Just thinking off the top of my head, it would be interesting to experiment with a way flutter could declare new syntax that allowed people to declare a "statefulwidget" rather than a "class" and have that desugar into the widget and state classes. maybe we just tell people to use codegen for this, though...

@munificent: @yjbanov has had similar ideas for a while and spent a bunch of time talking to me about them. I'm very interested in this, though figuring out how to do it in a way that doesn't directly couple the language to Flutter is challenging.

It would be really cool if the language offered some static metaprogramming facility where you could define your own "class-like" constructs and a way to define what vanilla Dart they desugar to without having to go full codegen. Something akin to https://herbsutter.com/2017/07/26/metaclasses-thoughts-on-generative-c/.

If we do this right, we might even be able to answer the requests for things like "data classes" and "immutable types" almost entirely at the library level.

My hope is that after non-nullable types, we can spend some real time thinking about metaprogramming.

@yjbanov: If we're allowed language changes, then my current favorite option is something like:

// stateless
widget Foo {
  build() {
    ... access widget props ...
  }
}

// want stateful?
widget Foo {
  // add a `state {}` block
  state {
    String bar;
  }

  build() {
    ... access widget and state props ...
  }
}

One problem with the status quo is that conceptually developers want to "add state to a widget". The current way of moving between stateless and stateful does not feel like adding or removing state.

I don't think metaprogramming is sufficient to solve "data classes" or "immutables". Those features require semantics not expressible in current Dart at all.

And without language changes, I was thinking of experimenting with the following idea:

class Foo extends WidgetWithState<int> {
  int initState( ) => 0;

  build(context, int state) => Button(
    onTap: (context, int state) {
      context.setState(state + 1);
    },
    child: Text('Counting $state'),
  );
}

This API also enabled react hooks-like capability.

This issue was moved by vsmenon from dart-lang/sdk#36700.

Metadata

Metadata

Assignees

No one assigned

    Labels

    requestRequests to resolve a particular developer problem

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions