Sobes.tech
Junior

What is the essence of abstraction?

sobes.tech AI

Answer from AI

Abstraction in Flutter, as in programming in general, boils down to hiding complex implementation details and providing a simplified interface for interaction. This is achieved by creating high-level representations that conceal underlying details and allow working with concepts rather than specific implementations.

Main ideas:

  • Hiding details: Complex logic or data structures are hidden behind a simple interface.
  • Simplifying usage: Developers interact with an abstract representation without delving into implementation details.
  • Increasing flexibility: Changes to internal implementation do not affect code that uses the abstraction, as long as the interface remains the same.
  • Enhancing reusability: Abstract components can be used in various parts of the application.

Examples in Flutter:

  • Widgets: Widgets are abstractions over UI elements. We use Container, Row, Column, and others without knowing their internal implementation details.
  • Asynchronous programming: Future and Stream abstract work with asynchronous operations, hiding details of working with streams and events.
  • Architectural patterns: Using patterns like BLoC, Provider, or Riverpod is a form of abstraction that separates UI and business logic.

Example code using abstraction:

// Abstract class for data source
abstract class DataSource {
  Future<String> fetchData();
}

// Implementation using HTTP
class HttpDataSource implements DataSource {
  @override
  Future<String> fetchData() async {
    // Complex logic for HTTP request
    return "Data from HTTP";
  }
}

// Implementation using local storage
class LocalDataSource implements DataSource {
  @override
  Future<String> fetchData() async {
    // Complex logic for local storage
    return "Data from local storage";
  }
}

// Class using the DataSource abstraction
class Repository {
  final DataSource dataSource;

  Repository(this.dataSource);

  Future<String> getData() {
    return dataSource.fetchData();
  }
}

In this example, Repository interacts only with the DataSource abstraction, not caring where the data comes from (HTTP, local storage, etc.). This makes it easy to change the data source without modifying the Repository code.

What is the essence of abstraction? — Flutter - sobes.tech