Java Syllabus

Dart Syllabus

Data Types

Definition: Data types in Dart specify the type of data that a variable can hold. Dart is a statically-typed language, meaning you need to declare the type of variable if it cannot be inferred.

Explanation: Dart provides several data types including primitive types and more complex types.

Primitive Data Types:

  • int: Integer value
  • double: Floating-point value
  • String: Sequence of characters
  • bool: Boolean value (true or false)

Example:

void main() {
            int num = 10;
            double price = 19.99;
            String name = 'Dart';
            bool isFun = true;
        
            print('Integer: \$num');
            print('Double: \$price');
            print('String: \$name');
            print('Boolean: \$isFun');
        }

Variables

Definition: Variables are containers for storing data values. Dart uses var for automatic type inference or explicit type declaration.

Explanation: Dart provides var for dynamic typing and explicit type declarations for static typing.

Example:

void main() {
            var mutableVariable = 10;
            final immutableVariable = 20;
            
            print('Mutable Variable: \$mutableVariable');
            print('Immutable Variable: \$immutableVariable');
            
            mutableVariable = 30;
            print('Updated Mutable Variable: \$mutableVariable');
        }

Loops

Definition: Loops are used to execute a block of code repeatedly based on a condition.

Explanation: Dart supports for, while, and do-while loops.

For Loop:

for (var i = 0; i < 5; i++) {
            print('Iteration: \$i');
        }

While Loop:

var i = 0;
        while (i < 5) {
            print('Iteration: \$i');
            i++;
        }

Do-While Loop:

var i = 0;
        do {
            print('Iteration: \$i');
            i++;
        } while (i < 5);

Conditions

Definition: Conditions control the flow of the program based on certain criteria.

Explanation: Dart supports conditional statements like if, else, and switch.

If-Else Statement:

void main() {
            var number = 10;
            if (number > 0) {
                print('Number is positive.');
            } else {
                print('Number is non-positive.');
            }
        }

Switch Statement:

void main() {
            var day = 3;
            switch (day) {
                case 1:
                    print('Monday');
                    break;
                case 2:
                    print('Tuesday');
                    break;
                case 3:
                    print('Wednesday');
                    break;
                case 4:
                    print('Thursday');
                    break;
                case 5:
                    print('Friday');
                    break;
                case 6:
                    print('Saturday');
                    break;
                case 7:
                    print('Sunday');
                    break;
                default:
                    print('Invalid day');
            }
        }

Functions

Definition: Functions are blocks of code that perform a specific task and can be invoked multiple times.

Explanation: Dart functions are declared using the void keyword if they don’t return a value or specify a return type otherwise.

Example:

int add(int a, int b) {
            return a + b;
        }
        
        void main() {
            var sum = add(5, 3);
            print('Sum: \$sum');
        }

Classes

Definition: Classes are blueprints for creating objects. They encapsulate data and methods to manipulate that data.

Explanation: Dart classes are defined using the class keyword. Dart also supports inheritance, mixins, and more advanced OOP features.

Example:

class Person {
            String name;
            int age;
        
            Person(this.name, this.age);
        
            void introduce() {
                print('Hi, I\'m \$name and I\'m \$age years old.');
            }
        }
        
        void main() {
            var person = Person('John', 30);
            person.introduce();
        }

Stateless and Stateful Widgets

Definition: In Flutter, widgets are the building blocks of the UI. There are two main types: Stateless and Stateful widgets.

Stateless Widgets: Stateless widgets are immutable and do not change their state once created. They are ideal for static content.

Stateful Widgets: Stateful widgets are mutable and can change their state during the lifetime of the widget. They are used for dynamic content that changes over time.

Stateless Widget Example:

import 'package:flutter/material.dart';

        class MyApp extends StatelessWidget {
            @override
            Widget build(BuildContext context) {
                return MaterialApp(
                    home: Scaffold(
                        appBar: AppBar(
                            title: Text('Stateless Widget Example'),
                        ),
                        body: Center(
                            child: Text('This is a Stateless Widget'),
                        ),
                    ),
                );
            }
        }

        void main() {
            runApp(MyApp());
        }

Stateful Widget Example:

import 'package:flutter/material.dart';

        class CounterApp extends StatefulWidget {
            @override
            _CounterAppState createState() => _CounterAppState();
        }

        class _CounterAppState extends State {
            int _counter = 0;

            void _incrementCounter() {
                setState(() {
                    _counter++;
                });
            }

            @override
            Widget build(BuildContext context) {
                return MaterialApp(
                    home: Scaffold(
                        appBar: AppBar(
                            title: Text('Stateful Widget Example'),
                        ),
                        body: Center(
                            child: Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                    Text('Button pressed: $_counter times'),
                                    ElevatedButton(
                                        onPressed: _incrementCounter,
                                        child: Text('Increment'),
                                    ),
                                ],
                            ),
                        ),
                    ),
                );
            }
        }

        void main() {
            runApp(CounterApp());
        }

StreamController, StreamBuilder, FutureProvider, FutureBuilder

StreamController: A StreamController in Dart is used to create and manage streams. It allows you to add events to the stream and listen for those events.

Explanation: A StreamController can be used to broadcast events or create single-subscription streams.

Example:

import 'dart:async';

        void main() {
            final streamController = StreamController();
        
            streamController.stream.listen((data) {
                print('Received: \$data');
            });
        
            streamController.add(1);
            streamController.add(2);
            streamController.close();
        }

StreamBuilder: StreamBuilder is a Flutter widget that builds itself based on the latest snapshot of asynchronous interaction with a Stream.

Explanation: StreamBuilder listens to a stream and rebuilds its child widgets based on the stream’s latest data.

Example:

import 'package:flutter/material.dart';
        import 'dart:async';
        
        void main() {
            runApp(MyApp());
        }
        
        class MyApp extends StatelessWidget {
            @override
            Widget build(BuildContext context) {
                return MaterialApp(
                    home: Scaffold(
                        appBar: AppBar(
                            title: Text('StreamBuilder Example'),
                        ),
                        body: StreamBuilder(
                            stream: Stream.periodic(Duration(seconds: 1), (count) => count),
                            builder: (context, snapshot) {
                                if (snapshot.connectionState == ConnectionState.waiting) {
                                    return Center(child: CircularProgressIndicator());
                                } else if (snapshot.hasError) {
                                    return Center(child: Text('Error: ${snapshot.error}'));
                                } else {
                                    return Center(child: Text('Count: ${snapshot.data}'));
                                }
                            },
                        ),
                    ),
                );
            }
        }

FutureProvider: FutureProvider is not a built-in Dart or Flutter class, but rather part of the Provider package used for state management. It provides a way to manage the state based on asynchronous computations.

Explanation: FutureProvider can be used to provide data that is obtained asynchronously, and it rebuilds its children when the future completes.

Example:

import 'package:flutter/material.dart';
        import 'package:provider/provider.dart';
        
        Future fetchData() async {
            await Future.delayed(Duration(seconds: 2));
            return 'Data loaded';
        }
        
        void main() {
            runApp(
                MultiProvider(
                    providers: [
                        FutureProvider(
                            create: (_) => fetchData(),
                            initialData: 'Loading...',
                        ),
                    ],
                    child: MyApp(),
                ),
            );
        }
        
        class MyApp extends StatelessWidget {
            @override
            Widget build(BuildContext context) {
                return MaterialApp(
                    home: Scaffold(
                        appBar: AppBar(
                            title: Text('FutureProvider Example'),
                        ),
                        body: Center(
                            child: Consumer(
                                builder: (context, data, _) {
                                    return Text(data);
                                },
                            ),
                        ),
                    ),
                );
            }
        }

FutureBuilder: FutureBuilder is a Flutter widget that builds itself based on the latest snapshot of interaction with a Future.

Explanation: FutureBuilder listens to a future and rebuilds its child widgets based on the future's latest result.

Example:

import 'package:flutter/material.dart';

        void main() {
            runApp(MyApp());
        }

        Future fetchData() async {
            await Future.delayed(Duration(seconds: 2));
            return 'Data loaded';
        }

        class MyApp extends StatelessWidget {
            @override
            Widget build(BuildContext context) {
                return MaterialApp(
                    home: Scaffold(
                        appBar: AppBar(
                            title: Text('FutureBuilder Example'),
                        ),
                        body: Center(
                            child: FutureBuilder(
                                future: fetchData(),
                                builder: (context, snapshot) {
                                    if (snapshot.connectionState == ConnectionState.waiting) {
                                        return CircularProgressIndicator();
                                    } else if (snapshot.hasError) {
                                        return Text('Error: ${snapshot.error}');
                                    } else {
                                        return Text('Result: ${snapshot.data}');
                                    }
                                },
                            ),
                        ),
                    ),
                );
            }
        }
Drag to resize