library_private_types_in_public_api and StatefulWidget

199

I encountered the same issue, it seems that now when you generate a StatefulWidget instead of returning say _ExampleState in the createState method it now returns State<Example> which avoids returning a private type. I ended up updating all of my widgets to this approach.

so

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();
  }
}

can be rewritten as

class Example extends StatefulWidget {
  // you can also now use a super initializer for key 
  // if you are using dart 2.17
  const Example({super.key});

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

class _ExampleState extends State<Example> {
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}
Share:
199
Maurice Raguse
Author by

Maurice Raguse

ask me

Updated on January 04, 2023

Comments

  • Maurice Raguse
    Maurice Raguse over 1 year

    After upgrade the linter to the new version (flutter_lints: 2.0.1) in my pubspec the linter enables this rule: library_private_types_in_public_api by default. I don't understand why. In my App project there are a lot of widget classes extended by StatefulWidget. The state class is always private. Example projects do it the same way. Can someone explain why this rule make sense?

    Btw.: I know i can disable this rule.

  • Roslan Amir
    Roslan Amir almost 2 years
    To use Dart 2.17 and higher, edit your pubspec.yaml and under environment: use this: sdk: ">=2.17.0 <3.0.0"