darkschneider666/fluttercodegenerationguidelines icon
public
Published on 6/2/2025
Flutter Code Generation Guidelines

Some Flutter code generation guidelines

Rules

Code Generation Guidelines

  1. A StatefulWidget class is generated in this way, setting a key in the constructor and using State<MyWidget> instead _MyWidgetState
    class MyWidget extends StatefulWidget {
      const MyWidget({super.key});
    
      @override
      State<MyWidget> createState() => _MyWidgetState();
    }
    
    class _MyWidgetState extends State<MyWidget> {
      @override
      Widget build(BuildContext context) {
        return Container();
      }
    }
    
  2. A StatelessWidget class is generated in this way, setting a key in the constructor
    class MyWidget extends StatelessWidget {
      const MyWidget({super.key});
    
      @override
      Widget build(BuildContext context) {
        return Container();
      }
    }
    
  3. A BLoC class is generated in this way
    class MyBloc extends Bloc<MyEvent, MyState> {
      MyBloc() : super(MyInitialState());
    
      @override
      Stream<MyState> mapEventToState(MyEvent event) async* {
        // Implement your event handling logic here
      }
    }
    
  4. A Repository class is generated in this way
    class MyRepository {
      Future<MyData> fetchData() async {
        // Implement your data fetching logic here
      }
    }
    
  5. A UseCase class is generated in this way
    class MyUseCase {
      final MyRepository repository;
    
      MyUseCase(this.repository);
    
      Future<MyData> execute() async {
        return await repository.fetchData();
      }
    }
    
  6. A Model class is generated in this way
    class MyModel {
      final String id;
      final String name;
    
      MyModel({required this.id, required this.name});
    
      factory MyModel.fromJson(Map<String, dynamic> json) {
        return MyModel(
          id: json['id'],
          name: json['name'],
        );
      }
    
      Map<String, dynamic> toJson() {
        return {
          'id': id,
          'name': name,
        };
      }
    }
    
  7. A DataSource class is generated in this way
    class MyDataSource {
      Future<MyModel> fetchData() async {
        // Implement your data fetching logic here
      }
    }
    
  8. Use a 'SizedBox' to add whitespace to a layout. Try using a 'SizedBox' rather than a 'Container'.

Performance Guidelines

  1. Use 'const' keyword for constant widget constructors and for constant widget parameters to improve performance

  2. Avoid unnecessary rebuilds by using const widgets

  3. Use ListView.builder for long lists to improve performance