Dart

#19
TIOBE#28
PYPL#16
GitHub#27
RedMonk#19
IEEESpectrum#19
JetBrains#15
Programming LanguageFlutterGoogleMobile DevelopmentCross-platformWeb Development

Programming Language

Dart

Overview

Dart is a programming language developed by Google, used with the Flutter framework for cross-platform mobile app development.

Details

Dart is an object-oriented programming language announced by Google in 2011. Initially designed as a JavaScript alternative for web development, it has achieved significant success in mobile app development through the Flutter framework. Dart features C-style syntax while emphasizing type safety and development efficiency. It includes modern language features such as garbage collection, asynchronous programming support, and type inference. With Flutter's popularity, it has become possible to develop iOS, Android, web, and desktop applications from a single codebase, dramatically reducing development costs. The Hot Reload feature allows code changes to be reflected instantly in the app, improving development efficiency.

Usage Examples

Hello World

// Basic output
void main() {
  print('Hello, World!');
}

// Multiple value output
void helloMultiple() {
  print('Hello, Dart!');
  print('Welcome to Flutter development!');
}

// Output with variables
void helloWithVariables() {
  String message = 'Hello, Dart!';
  String name = 'John';
  int age = 25;
  
  print(message);
  print('My name is $name and I am $age years old.');
  
  // Expression interpolation
  print('Next year I will be ${age + 1} years old.');
}

// Function example
String createGreeting(String name, int age) {
  return 'My name is $name and I am $age years old.';
}

void main() {
  print('Hello, World!');
  helloMultiple();
  helloWithVariables();
  
  String greeting = createGreeting('Smith', 30);
  print(greeting);
}

// Entry point example
void main() {
  print('Dart program started');
  
  // Asynchronous processing example
  fetchData().then((data) {
    print('Data: $data');
  });
  
  print('Main processing completed');
}

Future<String> fetchData() async {
  await Future.delayed(Duration(seconds: 1));
  return 'Sample data';
}

Variables and Data Types

// Variable declaration
void main() {
  // var - type inference
  var name = 'John Doe';        // String
  var age = 25;                 // int
  var height = 175.5;           // double
  var isStudent = true;         // bool
  
  // Explicit type specification
  String explicitString = 'Hello';
  int explicitInt = 42;
  double explicitDouble = 3.14;
  bool explicitBool = false;
  
  // dynamic - type determined at runtime
  dynamic dynamicValue = 'Initially a string';
  print(dynamicValue);
  dynamicValue = 123;
  print(dynamicValue);
  dynamicValue = true;
  print(dynamicValue);
  
  // Object - base class for all types
  Object objectValue = 'Object type';
  print(objectValue);
  
  // Constants
  const String constantString = 'Compile-time constant';
  final String finalString = 'Runtime constant';
  final currentTime = DateTime.now(); // Determined at runtime
  
  // Nullable types
  String? nullableString = null;
  int? nullableInt;
  
  // Null safety
  String nonNullableString = 'Non-nullable';
  // nonNullableString = null; // Compile error
  
  // Null coalescing operator
  String defaultValue = nullableString ?? 'Default value';
  
  // Numeric types
  int integer = 42;
  double floating = 3.14159;
  num number = 123; // Parent class of int and double
  
  // Number literals
  int binary = 0b1010;          // Binary
  int octal = 0o755;            // Octal
  int hexadecimal = 0xFF;       // Hexadecimal
  double scientific = 1.25e2;   // Scientific notation
  
  // Strings
  String singleQuote = 'Single quotes';
  String doubleQuote = "Double quotes";
  String multiLine = '''
  Multi-line
  string can be
  written like this
  ''';
  
  // String interpolation
  String interpolation = 'Name: $name, Age: $age';
  String expression = 'Next year I will be ${age + 1} years old';
  
  // Raw strings (ignore escape characters)
  String rawString = r'This \n will not \t be escaped';
  
  // Lists (arrays)
  List<String> fruits = ['apple', 'banana', 'orange'];
  List<int> numbers = [1, 2, 3, 4, 5];
  var mixedList = ['string', 123, true]; // List<Object>
  
  // List operations
  fruits.add('strawberry');
  fruits.insert(0, 'grape');
  fruits.remove('banana');
  
  // Fixed-length list
  List<int> fixedList = List.filled(3, 0); // [0, 0, 0]
  
  // Set (unique collection)
  Set<String> uniqueFruits = {'apple', 'banana', 'orange'};
  uniqueFruits.add('apple'); // Duplicates not added
  
  // Map (dictionary)
  Map<String, int> scores = {
    'Math': 85,
    'English': 92,
    'Science': 78
  };
  
  // Map operations
  scores['History'] = 80;
  scores.remove('Science');
  
  // Type casting
  Object obj = 'This is a string';
  String str = obj as String;
  
  // Type checking
  if (obj is String) {
    print('obj is String type: $obj');
  }
  
  // Type checking (negation)
  if (obj is! int) {
    print('obj is not int type');
  }
  
  print('=== Variables and Data Types Example ===');
  print('Name: $name');
  print('Age: $age');
  print('Height: $height');
  print('Student: $isStudent');
  print('Default value: $defaultValue');
  print('Fruits: $fruits');
  print('Unique fruits: $uniqueFruits');
  print('Scores: $scores');
  print('Raw string: $rawString');
  print('Type info: ${name.runtimeType}');
}

Functions and Control Flow

// Basic function
int add(int a, int b) {
  return a + b;
}

// Single-expression function (arrow function)
int multiply(int a, int b) => a * b;

// Named parameters
String greet({required String name, int age = 0, String? hometown}) {
  String message = 'Hello, $name!';
  if (age > 0) {
    message += ' You are $age years old.';
  }
  if (hometown != null) {
    message += ' From $hometown.';
  }
  return message;
}

// Positional parameters (optional)
String createMessage(String name, [int? age, String? city]) {
  String message = 'Name: $name';
  if (age != null) message += ', Age: $age';
  if (city != null) message += ', City: $city';
  return message;
}

// Variadic parameters
int sum(List<int> numbers) {
  return numbers.fold(0, (prev, element) => prev + element);
}

// Higher-order functions
List<T> processlist<T>(List<T> items, T Function(T) processor) {
  return items.map(processor).toList();
}

// Generic functions
T getFirst<T>(List<T> items) {
  if (items.isEmpty) {
    throw ArgumentError('List is empty');
  }
  return items.first;
}

// Async functions
Future<String> fetchUserData(int userId) async {
  // Simulate network processing
  await Future.delayed(Duration(seconds: 1));
  return 'User $userId data';
}

// Stream functions
Stream<int> countDown(int start) async* {
  for (int i = start; i >= 0; i--) {
    await Future.delayed(Duration(milliseconds: 500));
    yield i;
  }
}

void main() async {
  print('=== Function Examples ===');
  
  // Basic function calls
  print('Addition: ${add(5, 3)}');
  print('Multiplication: ${multiply(4, 6)}');
  
  // Named parameters
  print(greet(name: 'Smith', age: 25));
  print(greet(name: 'Johnson', hometown: 'London'));
  
  // Positional parameters
  print(createMessage('Brown'));
  print(createMessage('Wilson', 30));
  print(createMessage('Davis', 28, 'Boston'));
  
  // Variadic parameters
  print('Sum: ${sum([1, 2, 3, 4, 5])}');
  
  // Higher-order functions
  List<int> numbers = [1, 2, 3, 4, 5];
  List<int> doubled = processlist(numbers, (x) => x * 2);
  print('Doubled: $doubled');
  
  // Generic functions
  print('First fruit: ${getFirst(['apple', 'banana', 'orange'])}');
  print('First number: ${getFirst([10, 20, 30])}');
  
  // Async processing
  try {
    String userData = await fetchUserData(123);
    print('Fetched data: $userData');
  } catch (e) {
    print('Error: $e');
  }
  
  // Stream processing
  print('Countdown started:');
  await for (int count in countDown(5)) {
    print('Count: $count');
  }
  
  // Control structures
  demonstrateControlFlow();
}

void demonstrateControlFlow() {
  print('\n=== Control Flow Examples ===');
  
  // if-else statement
  int score = 85;
  if (score >= 90) {
    print('Excellent!');
  } else if (score >= 70) {
    print('Good.');
  } else {
    print('Need improvement.');
  }
  
  // Ternary operator
  String result = score >= 60 ? 'Pass' : 'Fail';
  print('Result: $result');
  
  // switch statement
  String grade = 'A';
  switch (grade) {
    case 'A':
      print('Excellent');
      break;
    case 'B':
      print('Good');
      break;
    case 'C':
      print('Average');
      break;
    default:
      print('Unknown grade');
  }
  
  // for loop
  print('for loop:');
  for (int i = 0; i < 5; i++) {
    print('  $i');
  }
  
  // for-in loop
  List<String> colors = ['red', 'blue', 'green'];
  print('for-in loop:');
  for (String color in colors) {
    print('  Color: $color');
  }
  
  // forEach
  print('forEach:');
  colors.forEach((color) => print('  Color: $color'));
  
  // while loop
  print('while loop:');
  int count = 0;
  while (count < 3) {
    print('  Count: $count');
    count++;
  }
  
  // do-while loop
  print('do-while loop:');
  int doCount = 0;
  do {
    print('  do-Count: $doCount');
    doCount++;
  } while (doCount < 3);
  
  // continue and break
  print('continue and break:');
  for (int i = 0; i < 10; i++) {
    if (i % 2 == 0) continue; // Skip even numbers
    if (i > 7) break;         // Stop if greater than 7
    print('  Odd: $i');
  }
  
  // try-catch-finally
  try {
    int divisionResult = 10 ~/ 0; // Integer division by zero
    print(divisionResult);
  } catch (e) {
    print('Error occurred: $e');
  } finally {
    print('Cleanup processing executed');
  }
  
  // assert statement (only active in debug mode)
  int value = 5;
  assert(value > 0, 'Value must be positive');
  print('Assert check completed');
}

Classes and Object-Oriented Programming

// Basic class
class Person {
  // Properties
  String name;
  int age;
  String? email; // Nullable property
  
  // Constructor
  Person(this.name, this.age, [this.email]);
  
  // Named constructor
  Person.withEmail(this.name, this.age, this.email);
  
  Person.unknown() : this('Unknown', 0);
  
  // Methods
  String introduce() {
    return 'My name is $name and I am $age years old.';
  }
  
  void haveBirthday() {
    age++;
    print('Happy ${age}th birthday, $name!');
  }
  
  // Getter
  String get description => '$name ($age years old)';
  
  // Setter
  set userEmail(String? newEmail) {
    if (newEmail != null && newEmail.contains('@')) {
      email = newEmail;
    } else {
      print('Invalid email address');
    }
  }
  
  // toString override
  @override
  String toString() {
    return 'Person{name: $name, age: $age, email: $email}';
  }
}

// Inheritance
class Student extends Person {
  String school;
  List<String> subjects;
  
  Student(String name, int age, this.school, this.subjects) 
      : super(name, age);
  
  // Method override
  @override
  String introduce() {
    return '${super.introduce()} I study at $school.';
  }
  
  void study(String subject) {
    if (subjects.contains(subject)) {
      print('$name is studying $subject.');
    } else {
      print('$subject is not enrolled.');
    }
  }
  
  // Additional getter
  String get academicInfo => '$school - Subjects: ${subjects.join(', ')}';
}

// Abstract class
abstract class Vehicle {
  String brand;
  String model;
  
  Vehicle(this.brand, this.model);
  
  // Abstract methods
  void start();
  void stop();
  
  // Concrete method
  String getInfo() => '$brand $model';
}

// Interface (implemented as abstract class)
abstract class Flyable {
  void fly();
  double get maxAltitude;
}

// Multiple inheritance from classes/interfaces
class Car extends Vehicle {
  int numberOfDoors;
  
  Car(String brand, String model, this.numberOfDoors) 
      : super(brand, model);
  
  @override
  void start() {
    print('Started $brand $model engine');
  }
  
  @override
  void stop() {
    print('Stopped $brand $model engine');
  }
}

class Airplane extends Vehicle implements Flyable {
  @override
  double maxAltitude = 12000.0; // meters
  
  Airplane(String brand, String model) : super(brand, model);
  
  @override
  void start() {
    print('Started $brand $model aircraft engine');
  }
  
  @override
  void stop() {
    print('Stopped $brand $model aircraft engine');
  }
  
  @override
  void fly() {
    print('$brand $model flying at max altitude ${maxAltitude}m');
  }
}

// Mixin
mixin Swimmer {
  void swim() {
    print('Swimming');
  }
  
  double get swimSpeed => 5.0; // km/h
}

mixin Walker {
  void walk() {
    print('Walking');
  }
  
  double get walkSpeed => 4.0; // km/h
}

// Class using mixins
class Amphibian with Swimmer, Walker {
  String name;
  
  Amphibian(this.name);
  
  void move() {
    print('$name is moving:');
    walk();
    swim();
    print('Walk speed: ${walkSpeed}km/h, Swim speed: ${swimSpeed}km/h');
  }
}

// Enums
enum Color {
  red,
  green,
  blue,
  yellow;
  
  // Enum methods
  String get displayName {
    switch (this) {
      case Color.red:
        return 'Red';
      case Color.green:
        return 'Green';
      case Color.blue:
        return 'Blue';
      case Color.yellow:
        return 'Yellow';
    }
  }
}

// Enhanced Enums
enum Planet {
  mercury(3.303e+23, 2.4397e6),
  venus(4.869e+24, 6.0518e6),
  earth(5.976e+24, 6.37814e6);
  
  const Planet(this.mass, this.radius);
  
  final double mass;           // kg
  final double radius;         // meters
  
  double get surfaceGravity => 6.67300E-11 * mass / (radius * radius);
}

void main() {
  print('=== Classes and Object-Oriented Programming Examples ===');
  
  // Basic class usage
  Person person1 = Person('John Doe', 25, '[email protected]');
  print(person1.introduce());
  print('Description: ${person1.description}');
  
  person1.haveBirthday();
  print(person1);
  
  // Named constructor
  Person person2 = Person.withEmail('Jane Smith', 30, '[email protected]');
  Person person3 = Person.unknown();
  
  // Setter usage
  person3.userEmail = '[email protected]';
  print('person3 email: ${person3.email}');
  
  // Inheritance example
  Student student = Student('Bob Johnson', 20, 'MIT', ['Math', 'Physics', 'Chemistry']);
  print(student.introduce());
  print('Academic info: ${student.academicInfo}');
  student.study('Math');
  student.study('English');
  
  // Abstract class and inheritance
  Car car = Car('Toyota', 'Prius', 4);
  print('Car info: ${car.getInfo()}');
  car.start();
  car.stop();
  
  Airplane airplane = Airplane('Boeing', '747');
  print('Airplane info: ${airplane.getInfo()}');
  airplane.start();
  airplane.fly();
  airplane.stop();
  
  // Mixin example
  Amphibian frog = Amphibian('Frog');
  frog.move();
  
  // Enum example
  Color favoriteColor = Color.blue;
  print('Favorite color: ${favoriteColor.displayName}');
  
  // Display all colors
  for (Color color in Color.values) {
    print('Color: ${color.name} (${color.displayName})');
  }
  
  // Enhanced enum example
  Planet earth = Planet.earth;
  print('Earth mass: ${earth.mass} kg');
  print('Earth radius: ${earth.radius} m');
  print('Earth surface gravity: ${earth.surfaceGravity.toStringAsFixed(2)} m/s²');
  
  // Type checking
  if (student is Person) {
    print('student is an instance of Person');
  }
  
  if (airplane is Flyable) {
    print('airplane is flyable');
  }
}

Asynchronous Programming

import 'dart:async';
import 'dart:math';

// Async function returning Future
Future<String> fetchDataFromAPI(String endpoint) async {
  print('API call started: $endpoint');
  
  // Simulate network delay
  await Future.delayed(Duration(seconds: 2));
  
  // Randomly decide success/failure
  if (Random().nextBool()) {
    return 'Data fetch successful: data from $endpoint';
  } else {
    throw Exception('Failed to fetch data from $endpoint');
  }
}

// Concurrent execution of multiple async operations
Future<List<String>> fetchMultipleData() async {
  List<Future<String>> futures = [
    fetchDataFromAPI('users'),
    fetchDataFromAPI('posts'),
    fetchDataFromAPI('comments'),
  ];
  
  try {
    // Wait for all operations to complete
    List<String> results = await Future.wait(futures);
    return results;
  } catch (e) {
    print('Error during concurrent processing: $e');
    rethrow;
  }
}

// Async operation with timeout
Future<String> fetchWithTimeout(String endpoint, {Duration timeout = const Duration(seconds: 5)}) async {
  try {
    return await fetchDataFromAPI(endpoint).timeout(timeout);
  } on TimeoutException {
    throw Exception('$endpoint: Timeout occurred');
  }
}

// Stream generating function
Stream<int> generateNumbers(int count) async* {
  for (int i = 1; i <= count; i++) {
    await Future.delayed(Duration(milliseconds: 500));
    yield i;
  }
}

// Stream transformation function
Stream<String> processNumbers(Stream<int> numbers) async* {
  await for (int number in numbers) {
    String processed = 'Number: $number (${number % 2 == 0 ? 'Even' : 'Odd'})';
    yield processed;
  }
}

// Async function simulating file reading
Future<String> readFile(String filename) async {
  print('File reading started: $filename');
  await Future.delayed(Duration(milliseconds: 800));
  
  if (filename.endsWith('.txt')) {
    return 'File content: contents of $filename';
  } else {
    throw ArgumentError('Unsupported file format: $filename');
  }
}

// Async processing with error handling
Future<void> processFiles(List<String> filenames) async {
  for (String filename in filenames) {
    try {
      String content = await readFile(filename);
      print('✅ $content');
    } catch (e) {
      print('❌ Error: $e');
    }
  }
}

// StreamController example
class DataProcessor {
  late StreamController<String> _controller;
  Stream<String> get stream => _controller.stream;
  
  DataProcessor() {
    _controller = StreamController<String>.broadcast();
  }
  
  void addData(String data) {
    _controller.sink.add('Processed: $data');
  }
  
  void addError(String error) {
    _controller.sink.addError('Error: $error');
  }
  
  void close() {
    _controller.close();
  }
}

// Completer example
Future<String> createCompleterExample() {
  Completer<String> completer = Completer<String>();
  
  // Execute task asynchronously
  Timer(Duration(seconds: 2), () {
    if (Random().nextBool()) {
      completer.complete('Async processing completed with Completer');
    } else {
      completer.completeError('Error occurred in Completer');
    }
  });
  
  return completer.future;
}

void main() async {
  print('=== Asynchronous Programming Examples ===');
  
  // Basic async processing
  try {
    String result = await fetchDataFromAPI('sample-endpoint');
    print('✅ $result');
  } catch (e) {
    print('❌ Error: $e');
  }
  
  print('\n--- Concurrent Processing Example ---');
  try {
    List<String> results = await fetchMultipleData();
    for (int i = 0; i < results.length; i++) {
      print('Result ${i + 1}: ${results[i]}');
    }
  } catch (e) {
    print('❌ Concurrent processing error: $e');
  }
  
  print('\n--- Timeout Processing Example ---');
  try {
    String result = await fetchWithTimeout('slow-endpoint', timeout: Duration(seconds: 1));
    print('✅ $result');
  } catch (e) {
    print('❌ Timeout error: $e');
  }
  
  print('\n--- Stream Processing Example ---');
  Stream<int> numberStream = generateNumbers(5);
  Stream<String> processedStream = processNumbers(numberStream);
  
  await for (String processed in processedStream) {
    print(processed);
  }
  
  print('\n--- File Processing Example ---');
  List<String> files = ['data.txt', 'config.txt', 'image.jpg', 'document.txt'];
  await processFiles(files);
  
  print('\n--- StreamController Example ---');
  DataProcessor processor = DataProcessor();
  
  // Listen to Stream
  StreamSubscription subscription = processor.stream.listen(
    (data) => print('Received: $data'),
    onError: (error) => print('Error received: $error'),
    onDone: () => print('Stream ended'),
  );
  
  // Send data
  processor.addData('Data 1');
  processor.addData('Data 2');
  processor.addError('Test error');
  processor.addData('Data 3');
  
  // Wait a bit then close
  await Future.delayed(Duration(milliseconds: 100));
  processor.close();
  
  print('\n--- Completer Example ---');
  try {
    String completerResult = await createCompleterExample();
    print('✅ $completerResult');
  } catch (e) {
    print('❌ Completer error: $e');
  }
  
  print('\n--- Future.value and Future.error Examples ---');
  Future<String> immediateSuccess = Future.value('Immediate success');
  Future<String> immediateError = Future.error('Immediate error');
  
  print(await immediateSuccess);
  
  try {
    await immediateError;
  } catch (e) {
    print('Immediate error: $e');
  }
  
  print('\n--- Stream Transformation Methods Examples ---');
  Stream<int> sourceStream = Stream.fromIterable([1, 2, 3, 4, 5]);
  
  // map: transform each element
  List<String> mapped = await sourceStream
      .map((i) => 'Item $i')
      .toList();
  print('Map result: $mapped');
  
  // where: filtering
  Stream<int> sourceStream2 = Stream.fromIterable([1, 2, 3, 4, 5, 6]);
  List<int> filtered = await sourceStream2
      .where((i) => i % 2 == 0)
      .toList();
  print('Filter result (even): $filtered');
  
  // take: get up to specified count
  Stream<int> sourceStream3 = Stream.fromIterable([1, 2, 3, 4, 5]);
  List<int> taken = await sourceStream3
      .take(3)
      .toList();
  print('Take result (first 3): $taken');
  
  // Subscription cleanup
  await subscription.cancel();
  
  print('\nAsynchronous programming examples completed.');
}

Flutter App Basic Structure

// Basic Flutter application example
// Requires flutter dependencies in pubspec.yaml

import 'package:flutter/material.dart';

// App entry point
void main() {
  runApp(MyApp());
}

// App root widget
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Dart & Flutter App',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: HomePage(),
    );
  }
}

// Home page widget
class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  int _counter = 0;
  String _message = 'Tap button to count up!';
  List<String> _items = [];
  
  void _incrementCounter() {
    setState(() {
      _counter++;
      _message = 'Count: $_counter';
      _items.add('Item $_counter');
    });
  }
  
  void _resetCounter() {
    setState(() {
      _counter = 0;
      _message = 'Reset!';
      _items.clear();
    });
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Dart & Flutter Demo'),
        actions: [
          IconButton(
            icon: Icon(Icons.refresh),
            onPressed: _resetCounter,
          ),
        ],
      ),
      body: Padding(
        padding: EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            // Message display
            Card(
              child: Padding(
                padding: EdgeInsets.all(16.0),
                child: Text(
                  _message,
                  style: Theme.of(context).textTheme.headlineSmall,
                  textAlign: TextAlign.center,
                ),
              ),
            ),
            
            SizedBox(height: 20),
            
            // Counter display
            Container(
              padding: EdgeInsets.all(20),
              decoration: BoxDecoration(
                color: Colors.blue.shade50,
                borderRadius: BorderRadius.circular(10),
                border: Border.all(color: Colors.blue),
              ),
              child: Column(
                children: [
                  Text(
                    'Counter',
                    style: TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  SizedBox(height: 10),
                  Text(
                    '$_counter',
                    style: TextStyle(
                      fontSize: 48,
                      fontWeight: FontWeight.bold,
                      color: Colors.blue,
                    ),
                  ),
                ],
              ),
            ),
            
            SizedBox(height: 20),
            
            // Item list
            Text(
              'Item List:',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
              ),
            ),
            
            SizedBox(height: 10),
            
            Expanded(
              child: _items.isEmpty
                  ? Center(
                      child: Text(
                        'No items yet',
                        style: TextStyle(
                          color: Colors.grey,
                          fontStyle: FontStyle.italic,
                        ),
                      ),
                    )
                  : ListView.builder(
                      itemCount: _items.length,
                      itemBuilder: (context, index) {
                        return Card(
                          margin: EdgeInsets.symmetric(vertical: 2),
                          child: ListTile(
                            leading: CircleAvatar(
                              child: Text('${index + 1}'),
                              backgroundColor: Colors.blue,
                              foregroundColor: Colors.white,
                            ),
                            title: Text(_items[index]),
                            subtitle: Text('Created: ${DateTime.now().toString().substring(11, 19)}'),
                            trailing: IconButton(
                              icon: Icon(Icons.delete, color: Colors.red),
                              onPressed: () {
                                setState(() {
                                  _items.removeAt(index);
                                });
                              },
                            ),
                          ),
                        );
                      },
                    ),
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Count up',
        child: Icon(Icons.add),
      ),
    );
  }
}

// Custom widget example
class CustomButton extends StatelessWidget {
  final String text;
  final VoidCallback onPressed;
  final Color? color;
  
  const CustomButton({
    Key? key,
    required this.text,
    required this.onPressed,
    this.color,
  }) : super(key: key);
  
  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      style: ElevatedButton.styleFrom(
        backgroundColor: color ?? Theme.of(context).primaryColor,
        padding: EdgeInsets.symmetric(horizontal: 20, vertical: 12),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(8),
        ),
      ),
      onPressed: onPressed,
      child: Text(
        text,
        style: TextStyle(
          fontSize: 16,
          fontWeight: FontWeight.w500,
        ),
      ),
    );
  }
}

// Data class example
class User {
  final String name;
  final int age;
  final String email;
  
  const User({
    required this.name,
    required this.age,
    required this.email,
  });
  
  // JSON conversion
  factory User.fromJson(Map<String, dynamic> json) {
    return User(
      name: json['name'] as String,
      age: json['age'] as int,
      email: json['email'] as String,
    );
  }
  
  // JSON conversion
  Map<String, dynamic> toJson() {
    return {
      'name': name,
      'age': age,
      'email': email,
    };
  }
  
  @override
  String toString() {
    return 'User(name: $name, age: $age, email: $email)';
  }
}

// State management example (simple counter store)
class CounterStore extends ChangeNotifier {
  int _count = 0;
  
  int get count => _count;
  
  void increment() {
    _count++;
    notifyListeners();
  }
  
  void decrement() {
    _count--;
    notifyListeners();
  }
  
  void reset() {
    _count = 0;
    notifyListeners();
  }
}

print('Flutter application basic structure defined.');
print('Works in actual Flutter projects.');
print('');
print('Required dependencies:');
print('- flutter/material.dart');
print('- Flutter SDK configuration in pubspec.yaml');

Advantages and Disadvantages

Advantages

  • Cross-platform Development: Single codebase for iOS, Android, web, and desktop apps
  • Hot Reload: Code changes reflected instantly in app, dramatically improving development efficiency
  • High Performance: Compiles to native code achieving high performance
  • Rich Widgets: Flutter's comprehensive UI component library
  • Type Safety: Static typing catches errors at compile time
  • Async Support: Excellent asynchronous programming with async/await and Streams

Disadvantages

  • Learning Cost: Need to learn new language and framework
  • Ecosystem: Limited libraries and tools compared to Java or JavaScript
  • App Size: Flutter apps tend to be relatively large
  • Platform-dependent Features: Additional implementation needed for native feature access
  • Debugging Complexity: Multi-platform specific debugging challenges

Reference Links

Official Documentation

Learning Resources

Development Tools