<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:ital,wght@0,300;0,400;0,500;0,600;0,700;1,300;1,400;1,500;1,600;1,700&family=DM+Mono:ital,wght@0,300;0,400;0,500;1,300;1,400;1,500&display=swap" rel="stylesheet"/>

All about SOLID Principles in Flutter: Examples and Best Practices

By Mihir Pipermitwala · · 12 min read

âš¡ TL;DR

Check out this guide on SOLID principles in Flutter by Mihir Pipermitwala, a software engineer from Surat. Learn with real-world examples!

SOLID is a set of five object-oriented design principles — Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, and Dependency Inversion — that in Flutter translate into separating widgets from business logic, depending on abstract service classes, and injecting dependencies (often via Bloc or Riverpod) so your code stays easy to maintain, extend, and test. In this article, we’ll take a look at the SOLID principles in the context of Flutter and provide real-world examples to help you understand them better, finishing with the interview questions that come up most often.

SOLID Principles Overview

SOLID is an acronym that stands for five principles of object-oriented programming:

  1. Single Responsibility Principle (SRP): A class should have only one reason to change.
  2. Open/Closed Principle (OCP): A class should be open for extension but closed for modification.
  3. Liskov Substitution Principle (LSP): Subtypes should be substitutable for their base types.
  4. Interface Segregation Principle (ISP): Clients should not be forced to depend on interfaces they don’t use.
  5. Dependency Inversion Principle (DIP): High-level modules should not depend on low-level modules. Both should depend on abstractions.

Now let’s dive into each principle and see how they apply in Flutter development.

Single Responsibility Principle (SRP)

The SRP states that a class should have only one reason to change. In other words, a class should have only one responsibility. This helps to keep the code clean, organized, and easy to maintain.

Let’s take an example of a class that handles both the UI rendering and the business logic. This is not a good design because if we want to change the UI, we have to modify the business logic code as well. Instead, we can separate the UI and the business logic into different classes to follow the SRP.

Here’s an example of how to separate the UI and business logic in Flutter:

Copy
class MyHomePage extends StatefulWidget {
  
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('My App'),
      ),
      body: Center(
        child: Text(
          'Hello, World!',
          style: TextStyle(fontSize: 30),
        ),
      ),
    );
  }
}

class HomePageViewModel {
  String getText() => 'Hello, World!';
}

In this example, the MyHomePage widget only handles the UI rendering, while the HomePageViewModel class handles the business logic. This separation makes it easier to modify each component independently without affecting the other.

Open/Closed Principle (OCP)

The OCP states that a class should be open for extension but closed for modification. This means that we should be able to add new features or behaviors to a class without changing its existing code. This helps to maintain the existing code and avoid introducing new bugs.

Let’s take an example of a class that handles the rendering of different shapes. We can use the OCP principle to allow the addition of new shapes without modifying the existing code.

Here’s an example of how to use the OCP principle in Flutter:

Copy
abstract class Shape {
  void draw();
}

class Circle implements Shape {
  
  void draw() => print('Drawing a circle.');
}

class Rectangle implements Shape {
  
  void draw() => print('Drawing a rectangle.');
}

class ShapePainter {
  final List<Shape> shapes;

  ShapePainter(this.shapes);

  void paint(Canvas canvas) {
    shapes.forEach((shape) => shape.draw());
  }
}

In this example, we have an abstract Shape class with a draw method that will be implemented by its concrete subclasses. The ShapePainter class takes a list of shapes and paints them on the canvas by calling their draw method. The same pattern shows up all the time in Flutter widgets — think of how a CustomPainter subclass can be extended with new painting behavior without touching the painter’s caller.

Now, let’s say we want to add a new shape, such as a triangle. We can do this without modifying the ShapePainter class by creating a new subclass of Shape:

Copy
class Triangle implements Shape {
  
  void draw() => print('Drawing a triangle.');
}

And then we can use it like this:

Copy
final shapes = [Circle(), Rectangle(), Triangle()];
final painter = ShapePainter(shapes);

This way, we can add new shapes without modifying the existing code, which makes it easier to maintain and extend the application.

Liskov Substitution Principle (LSP)

The LSP states that subtypes should be substitutable for their base types. This means that if we have a class A that is a subtype of class B, we should be able to use an object of type A wherever an object of type B is expected, without affecting the correctness of the program.

Let’s take an example of a class hierarchy that represents different types of animals. We can use the LSP to ensure that any subclass can be used interchangeably with its superclass.

Here’s an example of how to use the LSP in Flutter:

Copy
abstract class Animal {
  final String name;

  Animal(this.name);

  String speak();
}

class Dog extends Animal {
  Dog() : super('Dog');

  
  String speak() => 'Woof!';
}

class Cat extends Animal {
  Cat() : super('Cat');

  
  String speak() => 'Meow!';
}

class AnimalApp {
  void run() {
    final animals = [Dog(), Cat()];
    animals.forEach((animal) => print('${animal.name} says ${animal.speak()}'));
  }
}

In this example, we have an abstract Animal class with a name property and a speak method that will be implemented by its concrete subclasses. The AnimalApp class creates a list of animals and prints out their names and the sounds they make. In a Flutter app, the same idea applies to widgets: any widget that accepts a List<Widget> (a Column, Row, or Stack) must work correctly with any child widget, and any subclass you build must honor the base contract — for example, a custom RenderBox subclass must respect performLayout()’s contract or it breaks the widget tree.

Thanks to the LSP, we can treat each animal as an Animal object, even though they are actually Dog and Cat objects. This makes the code more flexible and easier to maintain.

Interface Segregation Principle (ISP)

The ISP states that clients should not be forced to depend on interfaces they don’t use. This means that we should break down large interfaces into smaller, more specialized ones, so that clients only need to implement the methods they actually use.

Let’s take an example of an interface that represents a shape. We can use the ISP to break down this interface into smaller interfaces that represent specific shape behaviors.

Here’s an example of how to use the ISP in Flutter:

Copy
abstract class Shape {
  double get area;
}

abstract class HasPerimeter {
  double get perimeter;
}

class Circle implements Shape, HasPerimeter {
  final double radius;

  Circle(this.radius);

  
  double get area => 3.14 * radius * radius;

  
  double get perimeter => 2 * 3.14 * radius;
}

class Square implements Shape, HasPerimeter {
  final double side;

  Square(this.side);

  
  double get area => side * side;

  
  double get perimeter => 4 * side;
}

In this example, we have an abstract Shape interface with a get area method, and an HasPerimeter interface with a get perimeter method. The Circle and Square classes implement both interfaces, since they have both an area and a perimeter.

By breaking down the Shape interface into smaller interfaces, we make it easier for clients to use only the methods they need. For example, if a client only needs to calculate the area of a shape, they can depend only on the Shape interface, and not on the HasPerimeter interface.

Dependency Inversion Principle (DIP)

The DIP states that high-level modules should not depend on low-level modules. Instead, both should depend on abstractions. This means that we should define interfaces or abstract classes for our dependencies, so that we can easily switch between different implementations without affecting the rest of the application.

Let’s take an example of a class that sends notifications. We can use the DIP to make this class more flexible, by defining an interface for its dependencies.

Here’s an example of how to use the DIP in Flutter:

Copy
abstract class NotificationService {
  Future<void> sendNotification(String message);
}

class EmailService implements NotificationService {
  
  Future<void> sendNotification(String message) async {
    // send email notification
  }
}

class PushNotificationService implements NotificationService {
  
  Future<void> sendNotification(String message) async {
    // send push notification
  }
}

class NotificationSender {
  final NotificationService _service;

  NotificationSender(this._service);

  Future<void> send(String message) => _service.sendNotification(message);
}

In this example, we have an abstract NotificationService interface with a sendNotification method, and two concrete implementations: EmailService and PushNotificationService. The NotificationSender class depends on the NotificationService interface, instead of depending directly on either EmailService or PushNotificationService.

By depending on an interface instead of a concrete implementation, we make it easier to switch between different notification services, without having to modify the NotificationSender class.

In real Flutter apps, state-management libraries are where DIP pays off the most. With Riverpod, you expose an abstract repository through a provider and swap the implementation freely — the real one in production, a fake in tests:

Copy
import 'package:flutter_riverpod/flutter_riverpod.dart';

abstract class AuthRepository {
  Future<void> signIn(String email, String password);
}

class FirebaseAuthRepository implements AuthRepository {
  
  Future<void> signIn(String email, String password) async {
    // real Firebase call
  }
}

final authRepositoryProvider = Provider<AuthRepository>(
  (ref) => FirebaseAuthRepository(),
);

A Bloc or Cubit that consumes AuthRepository via ref or its constructor never knows (or cares) whether it is talking to Firebase or an in-memory fake — which is exactly what DIP asks for.

SOLID Best Practices in Flutter

A few practical habits I’ve picked up applying SOLID to Flutter codebases:

  1. Split oversized widgets. If a build() method runs past a screen, extract sub-widgets — each one then has a single responsibility.
  2. Keep business logic out of widgets. Push it into ViewModels, Blocs, Cubits, or Riverpod notifiers so UI and logic change independently.
  3. Depend on abstract repositories. Define an abstract class for every service (auth, storage, API) and inject the concrete implementation via a provider or constructor.
  4. Design small contracts. Instead of one giant AppServices interface, expose small ones like AuthRepository or AnalyticsTracker so widgets only depend on what they use.
  5. Extend with subtypes, not edits. New behavior (a new shape, a new payment provider) should be a new class implementing the existing abstraction, not a modification of a stable class.

Common SOLID Interview Questions in Flutter

SOLID comes up constantly in Flutter interviews. These are the questions I hear most, with the shape of a good answer:

  1. What does SOLID stand for, and how does it apply to Flutter? Name the five principles and give one Flutter example each — e.g. SRP as widget/logic separation, DIP as abstract repositories injected via Riverpod or Bloc.
  2. How does the Single Responsibility Principle apply to widgets? A widget should do one thing: render. Fetching, validating, and transforming data belong in a separate class.
  3. How do you apply the Dependency Inversion Principle in Flutter? High-level classes (Bloc, ViewModel) depend on abstract interfaces; concrete implementations are injected via a service locator, provider, or constructor.
  4. What is the difference between OCP and LSP? OCP says you extend behavior by adding new subclasses; LSP says those subclasses must remain substitutable without breaking callers.
  5. Why does Interface Segregation matter in Dart? Dart has no interface keyword — every abstract class acts as one — so it’s tempting to build god-interfaces; splitting them keeps implementations honest.
  6. How does SOLID improve testability? Abstractions make it trivial to substitute fakes or mocks, so you can unit test a Cubit without spinning up Firebase or real network calls.

Conclusion

The SOLID principles are an important set of guidelines for writing maintainable and flexible software. By following these principles, we can create code that is easier to understand, modify, and extend.

In this article, we’ve covered the five SOLID principles, and provided real-world examples of how to use them in Flutter. We hope this article has helped you understand the importance of these principles, and how to apply them to your own Flutter projects.

FAQ

What are the SOLID principles in Flutter?

SOLID stands for five object-oriented design principles: Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, and Dependency Inversion. In Flutter they translate into separating widgets from business logic, adding new behavior through subclasses instead of edits, keeping contracts small, and depending on abstract service classes that you inject through providers, Bloc, or Riverpod.

How does the Single Responsibility Principle apply to Flutter widgets?

A widget should do exactly one job: render UI. Fetching data from an API, validating form input, and transforming results belong in separate classes such as a ViewModel, Bloc, or Riverpod notifier. When logic and rendering are separated, you can change the screen’s appearance without touching business rules, and unit-test the logic without mounting widgets.

How do you apply the Dependency Inversion Principle in Flutter?

Define an abstract class for every service your app depends on, such as an AuthRepository, then have high-level classes like Blocs or ViewModels depend only on that abstraction. Inject the concrete implementation — Firebase in production, an in-memory fake in tests — through a Riverpod provider, service locator, or constructor parameter, so implementations can be swapped without changing callers.

Why is SOLID important in Flutter app architecture?

Applying SOLID keeps large Flutter codebases maintainable as features and team size grow. It prevents oversized widget classes that mix UI with logic, makes new features extendable without modifying stable code, and makes testing far easier because abstractions let you substitute fakes or mocks. The result is code that is easier to understand, extend, and refactor safely.

Mihir Pipermitwala

Written by Mihir Pipermitwala

Senior Full Stack Consultant & Mobile Engineering Specialist building user-focused applications in healthcare with Flutter, Dart and React Native. I write about what I actually build and test — every tutorial here comes from real project work.

More about Mihir →
Scroll down to load comments...
Related Blogs
Add an MCP Server to Your Flutter/Dart Tooling

Add an MCP Server to Your Flutter/Dart Tooling

Integrate a Model Context Protocol (MCP) server into your Flutter/Dart workflow. Step-by-step setup with Claude Code and real-world use cases.

AI TOOLSMCPFLUTTERDARTDEVELOPER TOOLS

October 06, 2026

Flutter On-Device LLM: Run Gemma & Llama Locally (2026)

Flutter On-Device LLM: Run Gemma & Llama Locally (2026)

Run on-device LLMs in Flutter using gemma_flutter and MediaPipe LLM Inference. No API keys, no internet — real-time AI on Android and iOS.

FLUTTERAI MLON DEVICE LLMGEMMALLAMA

September 24, 2026

How to Change minSdkVersion in Flutter: 2 Simple Approaches

How to Change minSdkVersion in Flutter: 2 Simple Approaches

Step-by-step guide to change the minSdkVersion in Flutter for Android. Learn how to configure local.properties or build.gradle for both new and old Flutter versions.

ANDROIDFLUTTERFLUTTER DEVELOPMENTMIN SDK VERSION

July 20, 2023

All about SOLID Principles in Flutter: Examples and Best Practices

All about SOLID Principles in Flutter: Examples and Best Practices

Check out this guide on SOLID principles in Flutter by Mihir Pipermitwala, a software engineer from Surat. Learn with real-world examples!

DARTFLUTTERSOLID PRINCIPLES

April 11, 2023

Related Tutorials
A Comprehensive Guide to Flutter Buttons: Choosing the Right One for Your App

A Comprehensive Guide to Flutter Buttons: Choosing the Right One for Your App

Complete guide to Flutter Button widgets. Learn how to use ElevatedButton, TextButton, OutlinedButton, IconButton, CupertinoButton, and FAB with examples.

CUPERTINO BUTTONELEVATED BUTTONFLOATING ACTION BUTTONFLUTTERFLUTTER BUTTON

April 17, 2024

Show an Offline Message for No Internet in Flutter

Show an Offline Message for No Internet in Flutter

You have to use the 'Connectivity Flutter Package' to achieve this feature on your App. This package helps to know whether your device is online or offline.

CONNECTIVITY PLUSDEPENDENCIESFLUTTERFLUTTER DEVELOPMENTFLUTTER PACKAGES

April 09, 2024

Mastering TabBar & TabBarView in Flutter: A Complete Guide

Mastering TabBar & TabBarView in Flutter: A Complete Guide

Implement TabBar and TabBarView in Flutter step by step — customize tab indicators, enable scrollable tabs, and change tabs programmatically.

CODINGDEFAULT TAB CONTROLLERFLUTTERLEARN TO CODETAB CONTROLLER

July 26, 2023

File Manipulation in Flutter: Best Practices & Examples

File Manipulation in Flutter: Best Practices & Examples

Master Flutter file manipulation — permission management, directory handling, and practical read-write scenarios to elevate your app's file handling.

CODINGFLUTTERFLUTTER DEVELOPMENTFLUTTER FILE OPERATIONFLUTTER PATH PROVIDER

June 30, 2023

Related Recommended Services
Visual Studio Code for the Web

Visual Studio Code for the Web

Build with Visual Studio Code, anywhere, anytime, in your browser.

IDEVISUAL STUDIOVISUAL STUDIO CODEWEB
Renovate | Automated Dependency Updates

Renovate | Automated Dependency Updates

Renovate Bot keeps source code dependencies up-to-date using automated Pull Requests.

AUTOMATED DEPENDENCY UPDATESBUNDLERCOMPOSERGITHUBGO MODULES
Best XML Formatter and XML Beautifier

Best XML Formatter and XML Beautifier

Online XML Formatter will format xml data, helps to validate, and works as XML Converter. Save and Share XML.

XMLXML BEAUTIFIERXML CONVERTERXML FORMATXML FORMATTER
Kubecost | Kubernetes cost monitoring and management

Kubecost | Kubernetes cost monitoring and management

Kubecost started in early 2019 as an open-source tool to give developers visibility into Kubernetes spend. We maintain a deep commitment to building and supporting dedicated solutions for the open source community.

CLOUDKUBECOSTKUBERNETESOPEN SOURCESELF HOSTED
Related Recommended Stories
How GitHub reduced testing time for iOS apps with new runner features

How GitHub reduced testing time for iOS apps with new runner features

Learn how GitHub used macOS and Apple Silicon runners for GitHub Actions to build, test, and deploy our iOS app faster.

IOSGITHUBTESTINGRUNNER
5 ways to transform your workflow using GitHub Copilot and MCP

5 ways to transform your workflow using GitHub Copilot and MCP

Learn how to streamline your development workflow with five different MCP use cases.

AGENT MODECODING AGENTCOPILOTFIGMAGITHUB
One weird trick for powerful Git aliases

One weird trick for powerful Git aliases

Advanced Git Aliases

ALIASALIAS TEMPLATEATLASSIANBITBUCKETGIT
Awesome Python

Awesome Python

An opinionated list of awesome Python frameworks, libraries, software and resources

AWESOMEAWESOME PYTHONCOLLECTIONSGITHUBPYTHON
Related Recommended Tools
Find out what websites are built with - Wappalyzer

Find out what websites are built with - Wappalyzer

Find out the technology stack of any website. Create lists of websites and contacts by the technologies they use.

ADD ONSANALYTICSAPP STOREAPPLEBOOKING
Sourcetree | Free Git GUI for Mac and Windows

Sourcetree | Free Git GUI for Mac and Windows

A Git GUI that offers a visual representation of your repositories. Sourcetree is a free Git client for Windows and Mac.

GITGITHUBGITLABATLASSIANBITBUCKET
Related Recommended Videos