VeryGoodOpenSource/very_good_analysis

library_private_types_in_public_api for statefulWidget

Closed this issue · 6 comments

Describe the bug
library_private_types_in_public_api is too annoying for StatefulWidget

To Reproduce
Create a statefulWidget

class Example extends StatefulWidget {
  const Example({ Key? key }) : super(key: key);

  @override
  _ExampleState createState() => _ExampleState();
}

class _ExampleState extends State<Example> {
  @override
  Widget build(BuildContext context) {
    return Container(
      
    );
  }
}

Any idea to avoid this ?

Hi @RealBug 👋
Thanks for opening an issue!

In this case, I'd recommend adjusting the return type to State<Example> like:

class Example extends StatefulWidget {
  const Example({ Key? key }) : super(key: key);

  @override
  State<Example> createState() => _ExampleState();
}

class _ExampleState extends State<Example> {
  @override
  Widget build(BuildContext context) {
    return Container(
      
    );
  }
}

Let me know if that helps 👍

Hi @felangel.

I'm working on a project that uses MobX and MobX has this pattern:

class SampleStore = _SampleStoreBase with _$SampleStore;

abstract class _SampleStoreBase with Store {}

In this case, i think its ok to remove _ from Base, as it asbtract.

What do you think? 🤔

In this case, I’d recommend adjusting the return type to State<Example> like:

Using State<Example> instead of the concrete _ExampleState type might be equivalent in most cases since there’s only one State class per Widget class.

Nevertheless, when implementing the of(context)-like pattern to access a public member from the private State class, there’s a need to specify the concrete _AppState type to know where the methods to be accessed come from.

class App extends StatefulWidget {
  const App({Key? key}) : super(key: key);

  @override
  _AppState createState() => _AppState();

  static _AppState? of(BuildContext context) =>
      context.findAncestorStateOfType<_AppState>();
}

class _AppState extends State<App> {
  Locale? _locale;

  void setLocale(Locale locale) {
    setState(() {
      _locale = locale;
    });
  }
}

Which may be accessed like:

App.of(context)?.setLocale(Locale('ca'));

Do you know a better way to approach this without making the _AppState public?—Which, indeed, may solve the problem.

Hi @felangel.

I'm working on a project that uses MobX and MobX has this pattern:

class SampleStore = _SampleStoreBase with _$SampleStore;

abstract class _SampleStoreBase with Store {}

In this case, i think its ok to remove _ from Base, as it asbtract.

What do you think? 🤔

Yup I don’t see a problem with making it public.

@albertms10 I would recommend making AppState public in that case because consumers of the API shouldn’t receive an instance of a private class. If of is public it should return an instance of a public class.

Closing for now but feel free to leave any additional comments/questions and I’m happy to continue the conversation 👍