12 Prompts for Flutter: Widgets, State Management, and Animations

12 Prompts for Flutter: Widgets, State Management, and Animations

Flutter is a powerful UI toolkit, but writing boilerplate for widgets, state management, and animations can slow you down. Using well-crafted prompts with AI assistants (like ChatGPT or Claude) can help you generate production-ready code in seconds. In this guide, I’ve curated 12 practical prompts organized by experience level: basic, advanced, and expert. Each prompt includes a specific task, the exact prompt to use, and an example result you can expect — grounded in official Flutter documentation and popular packages like Bloc and Riverpod.

Basic Prompts: Widgets and Forms

1. Generate a StatelessWidget with Custom Properties

Task: Create a reusable user avatar widget with a placeholder while loading.

Prompt: "Write a Flutter StatelessWidget called UserAvatar that takes imageUrl, radius, and placeholderIcon parameters. Show a loading spinner while the image downloads and an error icon if the network request fails. Use ClipOval and Image.network."

Example result: The AI returns a widget with a FutureBuilder that handles loading and error states. Here's the key part:

class UserAvatar extends StatelessWidget {
  final String imageUrl;
  final double radius;
  final IconData placeholderIcon;
  // constructor...
  @override
  Widget build(BuildContext context) {
    return ClipOval(
      child: Image.network(
        imageUrl,
        width: radius * 2,
        height: radius * 2,
        fit: BoxFit.cover,
        loadingBuilder: (context, child, progress) => progress == null
            ? child
            : const Center(child: CircularProgressIndicator()),
        errorBuilder: (context, error, stack) => Icon(placeholderIcon),
      ),
    );
  }
}

2. Refactor a StatefulWidget to Use Form with Validation

Task: Turn a login screen into a proper Form with validators.

Prompt: "Convert this login form to a Flutter Form with validators for email and password. Add a GlobalKey<FormState> and show a SnackBar on success."

Example result: The code includes TextFormField widgets with validators. For example, the email validator checks for a simple regex. The build method uses Form and ElevatedButton to validate and submit.

3. Create a Custom Button Component

Task: Build a reusable GradientButton that behaves like ElevatedButton.

Prompt: "Create a Flutter widget called GradientButton that extends StatelessWidget and accepts onPressed, text, and gradient. Use InkWell and Container with BoxDecoration. The button must have rounded corners and a shadow elevation."

Example result: A component with a Gradient parameter and BoxShadow styling, ready for reuse in multiple screens.

Advanced Prompts: State Management with Bloc and Riverpod

4. Implement a Login Flow with Bloc

Task: Create a LoginBloc with events and states.

Prompt: "Design a Bloc for authentication: events LoginSubmitted, LoginFailed, states LoginInitial, LoginLoading, LoginSuccess, LoginFailure. Include a repository interface for dependency injection."

Example result: You get a LoginBloc class with mapEventToState (or on if you're using Bloc 8). The LoginBloc uses an AuthRepository to call the backend and emits LoginSuccess or LoginFailure accordingly.

5. Migrate a Counter from setState to Riverpod

Task: Replace a StatefulWidget counter with Riverpod's StateProvider.

Prompt: "Use Riverpod to refactor a simple counter app. Add a StateProvider<int> and two buttons that increment and decrement. Wrap the counter display in a Consumer or ConsumerWidget."

Example result: The prompt yields a StateProvider definition and a ConsumerWidget that reads the provider. The code uses ref.watch, and the button callbacks call ref.read(counterProvider.notifier).state++.

final counterProvider = StateProvider<int>((ref) => 0);
class CounterWidget extends ConsumerWidget {
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final count = ref.watch(counterProvider);
    return Text('$count');
  }
}

6. Build an Infinite Scroll Pagination with Bloc

Task: Fetch paginated data from an API and load more when the user scrolls.

Prompt: "Create a PaginatedListCubit that loads a list of posts with page and hasReachedEnd parameters. Use ScrollController in the UI to detect when to load the next page."

Example result: The Bloc's loadNextPage method fetches new items and appends them to the List<Post>. The UI uses a ListView.builder with an itemBuilder that checks if hasReachedEnd and shows a loading indicator at the bottom.

7. Use Freezed for Immutable State Models

Task: Eliminate boilerplate in Bloc states.

Prompt: "Model a HomeState using Freezed and json_serializable. Include status, posts, and errorMessage fields. Generate the .freezed.dart file using build_runner."

Example result: The AI provides a home_state.dart file with @freezed abstract class and factory HomeState. Also includes instructions for running flutter pub run build_runner build.

Expert Prompts: Animations and Performance

8. Create a Staggered Animation with a Custom AnimationController

Task: Animate a progress curve and a button simultaneously with a single controller.

Prompt: "Write a Flutter stateful widget that uses AnimationController with duration 2 seconds. Create two animations: first slides the title from left, then the button fades in. Use Interval on the CurvedAnimation for stagger."

Example result: The code defines _controller, _titleAnimation, and _buttonAnimation. In build(), you use an AnimatedBuilder to apply transforms and opacity to each child.

9. Use TweenAnimationBuilder for a Counter

Task: Animate a number from zero to a target value.

Prompt: "Create a Flutter widget that animates a counter from 0 to 1000 using TweenAnimationBuilder. Add a Duration of 2 seconds and a Curves.easeOut curve. Display the value with a thousand separator."

Example result: The widget automatically starts the tween on build. The builder receives the current value and formats it with NumberFormat from intl.

10. Implement a Hero Animation Between Routes

Task: Create a smooth image transition from a list to a detail screen.

Prompt: "Use Hero widget to animate a network image from a list item to a detail page. Set both Hero tags to the same string, for instance post-image-${post.id}. Add a MaterialPageRoute with FullscreenDialog false."

Example result: The list tile's image and the detail page's image are wrapped in Hero. The transition works automatically when pressing the tile.

11. Create an AnimatedBuilder for a Custom Side Menu

Task: Build a slide-in sidebar driven by a boolean.

Prompt: "Create a widget with an AnimationController that slides a menu from the left edge. Use AnimatedBuilder to compute the Matrix4.translationValues. Add a drag handle and close button."

Example result: The menu is positioned with Transform.translate, and the controller's value is converted to an offset. The example includes a GestureDetector to toggle the menu.

12. Optimize Rebuilds with const and RepaintBoundary

Task: Improve performance of a complex list.

Prompt: "Refactor a Flutter build method using const constructors and add RepaintBoundary around expensive widgets. Explain the benefit of avoiding unnecessary rebuilds."

Example result: The code marks constant widgets as const, reducing allocations. RepaintBoundary treats the child as a separative layer, so the framework skips repainting it when the rest of the screen changes. This is a best practice mentioned in the Flutter performance documentation.

Conclusion

These 12 prompts cover the most common Flutter tasks, from basic widgets to advanced state management and animation techniques. When using AI prompts, always verify the generated code against the official Flutter documentation at docs.flutter.dev and pub.dev. Whether you're starting with Flutter or you're an experienced developer, a well-formed prompt can save hours of debugging and keep your code clean and maintainable.

Try these prompts in your next project, and don't forget to adapt them to your specific use case. If you have a favorite prompt, share it in the comments!

← All posts

Comments