Dart is a rich language with many features. As we delve deeper, we'll cover some key concepts that will help you write more efficient and maintainable Flutter apps.
1. Async/Await and Futures π
Dart has built-in support for asynchronous programming, which is crucial for IO-bound work like loading files or making network requests.
Future<String> fetchUserData() {// Simulate a network requestreturnFuture.delayed(Duration(seconds:2), () =>'User Data');}voidgetUserData() async {String userData =awaitfetchUserData();print(userData); // Prints: User Data}
2. Streams π
Streams provide a way to respond to a series of data over time, like user input or a file being read.
Stream<int> countStream(int max) async* {for (int i =1; i <= max; i++) {yield i; // Pauses execution, returns the value, then continues from here when resumedawaitFuture.delayed(Duration(seconds:1)); }}voidlistenToStream() {countStream(5).listen((int value) {print(value); // Prints 1, 2, 3, 4, 5 (each on a new line, once per second) });}
3. Collections (List, Set, Map) ποΈ
Dart has powerful collection types like Lists, Sets, and Maps.
Leverage Object-Oriented Programming (OOP) principles to create custom classes.
classPerson {String name;int age;Person(this.name, this.age);voidgreet() {print('Hello, my name is $name and I am $age years old.'); }}voidcreatePerson() {Person person =Person('Alice', 30); person.greet(); // Prints: Hello, my name is Alice and I am 30 years old.}
Assignments π
Reinforce your learning with these exercises:
These topics are fundamental for working effectively with Flutter. By understanding these Dart concepts, you'll be well-equipped to tackle more complex tasks in your Flutter projects.
Up next, delve deeper into & State Management to learn how to create dynamic and responsive user interfaces!