Recap - Data Fetcher
Part of the Object Oriented Programming section of Coddy's Dart journey — lesson 81 of 110.
Challenge
EasyLet's build a DataFetcher class that brings together all the async OOP concepts from this chapter! You'll create a data service that uses async initialization, async methods for fetching individual items, and a stream for delivering multiple results over time.
You'll organize your code into two files:
data_fetcher.dart: Create aDataFetcherclass that simulates fetching data from a remote source. Your class should have:- A final
Stringfield calledsourcethat stores where the data comes from - A private constructor that initializes the source
- A static async factory method
connect(String sourceName)that returns aFuture<DataFetcher>. Simulate a connection delay of 100 milliseconds, then return a new instance with the source set to the provided name - An async method
fetchItem(int id)that returns aFuture<String>. Simulate a 50 millisecond delay, then return a string in the format:[source]-Item-[id] - A stream generator method
fetchMultiple(int count)that returns aStream<String>. This should yield items for IDs from 1 up to and includingcount, using yourfetchItemmethod for each one (await each fetch before yielding)
- A final
main.dart: Import your data fetcher and demonstrate all three async patterns working together:- Print
Connecting to data source... - Use the async factory to connect to a source named
CloudDB - Print
Connected to [source]using the fetcher's source field - Print an empty line
- Print
Fetching single item: - Fetch and print the item with ID
42 - Print an empty line
- Print
Fetching multiple items: - Use
await forto iterate throughfetchMultiple(3)and print each item - Print an empty line
- Print
All operations complete!
- Print
This challenge combines the static async factory pattern for initialization, regular async methods for single operations, and async* with yield for streaming multiple results. Notice how the stream method can call other async methods internally!
Expected output:
Connecting to data source...
Connected to CloudDB
Fetching single item:
CloudDB-Item-42
Fetching multiple items:
CloudDB-Item-1
CloudDB-Item-2
CloudDB-Item-3
All operations complete!Try it yourself
import 'data_fetcher.dart';
void main() async {
// TODO: Print 'Connecting to data source...'
// TODO: Use the async factory to connect to a source named 'CloudDB'
// TODO: Print 'Connected to [source]' using the fetcher's source field
// TODO: Print an empty line
// TODO: Print 'Fetching single item:'
// TODO: Fetch and print the item with ID 42
// TODO: Print an empty line
// TODO: Print 'Fetching multiple items:'
// TODO: Use 'await for' to iterate through fetchMultiple(3) and print each item
// TODO: Print an empty line
// TODO: Print 'All operations complete!'
}
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesLibraries & ImportsIntroduction to OOPClasses vs ObjectsThe this KeywordMethodsInstance VariablesConstructor BasicsRecap - Simple Calculator4Null Safety
Intro to Null SafetyNullable vs Non-NullableThe ? and ! OperatorsLate Keyword & Null SafetyNull-Aware OperatorsNull Safety in ClassesRecap - User Profile System7Abstract Classes & Interfaces
Abstract ClassesAbstract MethodsInterfaces in DartImplicit InterfacesImplementing vs ExtendingMultiple InterfacesRecap - Shape Calculator10Collections & Generics
List, Set, Map OverviewType-Safe CollectionsGeneric ClassesGeneric MethodsGeneric ConstraintsIterable & IteratorRecap - Generic Storage13Advanced OOP Concepts
Composition vs InheritanceExtension MethodsCallable ClassesSealed Classes (Dart 3)Records (Dart 3)Patterns & Matching (3.0)Enums with Methods16Project: Library Management
Project OverviewBook and User Classes2Constructors in Dart
Default ConstructorNamed ConstructorsInitializer ListsConstant ConstructorsFactory ConstructorsRedirecting ConstructorsRecap - Shape Builder5Encapsulation
Public vs Private MembersThe _ Prefix ConventionLibrary-Level PrivacyGetters & Setters DepthInformation HidingRecap - Student Records8Mixins
Introduction to MixinsCreating MixinsUsing Multiple Mixinson Keyword in MixinsMixin vs InheritanceMixin vs InterfaceRecap - Animal System11Special Methods
toString() OverridehashCode & == OverrideComparable Interfacecall() MethodnoSuchMethod OverrideRecap - Custom Collection14Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy Pattern3Class Properties
Instance vs Static MembersFinal & Const FieldsLate VariablesStatic Methods & FieldsGetters and SettersRecap - Bank Account Manager6Inheritance
Basic InheritanceThe super KeywordMethod OverridingThe @override AnnotationThe final Class KeywordConstructors & InheritanceRecap - Employee Hierarchy9Polymorphism
Polymorphism BasicsPolymorphism via InterfacesRuntime Type CheckingThe is & as OperatorsCovariant KeywordRecap - Payment Processor12Async OOP
Futures & async/awaitStreams BasicsStream ControllersAsync ConstructorsAsync in Class MethodsRecap - Data Fetcher