Home > Back-end >  library_private_types_in_public_api and StatefulWidget
library_private_types_in_public_api and StatefulWidget

Time:05-14

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.

CodePudding user response:

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