0% found this document useful (0 votes)
4 views89 pages

MAD solution

The document provides an introduction to Dart programming, covering its features, data types, and key concepts such as classes, constructors, inheritance, and polymorphism. It highlights the importance of Dart in modern application development, particularly with the Flutter framework, emphasizing cross-platform capabilities and fast development. Additionally, it explains decision-making, loops, and the use of getters and setters in Dart, along with examples for better understanding.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views89 pages

MAD solution

The document provides an introduction to Dart programming, covering its features, data types, and key concepts such as classes, constructors, inheritance, and polymorphism. It highlights the importance of Dart in modern application development, particularly with the Flutter framework, emphasizing cross-platform capabilities and fast development. Additionally, it explains decision-making, loops, and the use of getters and setters in Dart, along with examples for better understanding.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 89

Unit-1 Introduction to Dart Programming

2 Marks Questions
1. What is Dart?
Dart is an open-source, general-purpose programming language developed by Google. It is
object-oriented and supports both ahead-of-time (AOT) and just-in-time (JIT) compilation.
Dart is mainly used for developing mobile applications using the Flutter framework, as well
as web, desktop, and server applications. Dart’s syntax is similar to Java or JavaScript,
making it easy to learn for beginners.

2. List two key features of Dart.


1. Object-Oriented: Dart treats everything as an object, including numbers, strings, and
even functions. This makes code easier to organize and reuse.
2. Cross-Platform Development: Dart can be used to create apps for Android, iOS, web,
and desktop from a single codebase using Flutter.
(Other features you could write: Strong typing, asynchronous programming with
async/await, and rich standard libraries.)

3. Mention any two data types used in Dart.


1. int: Used to store integer (whole) numbers. Example: int age = 20;
2. String: Used to store a sequence of characters or text. Example: String name =
"Vishva";
Other Dart data types include double, bool, List, and Map.

4. Define a variable in Dart and give an example.


In Dart, a variable is a container that holds data which can be changed during program
execution. Dart is a statically typed language, meaning each variable has a specific type.
Example:
int marks = 85;
String studentName = "Anjali";
Here, int is used for numbers and String for text. Variables must be declared before they are
used.

5. What is the purpose of the final keyword in Dart?


The final keyword is used to declare a variable whose value cannot be changed after it is
set. It is initialized only once and is immutable after that. It is useful when you want to
protect a variable from accidental modification.
Example:
final city = "Ahmedabad"; // city can't be changed later
You can assign final variables at runtime, unlike const.

6. Explain the difference between const and final in Dart.


Both const and final are used to declare unchangeable (immutable) variables, but they have
key differences:

Keyword Description

Value is set only once at runtime. Can be assigned based on calculation or user
final
input.

Value is set at compile-time and is a constant for the life of the program. Cannot
const
depend on runtime data.

Example:
final currentTime = DateTime.now(); // OK
const pi = 3.14; // Must be constant

7. What is a class in Dart?


A class in Dart is a blueprint for creating objects. It groups data and functions into a single
unit. A class contains:
• Fields (variables)
• Methods (functions)
• Constructors
Example:
class Student {
String name = "Ravi";

void display() {
print("Name: $name");
}
}
Classes help organize code and enable object-oriented programming.

8. What is a constructor in Dart?


A constructor is a special function used to create an object and initialize its variables when
the class is instantiated. Dart provides a default constructor, but you can also create custom
constructors.
Example:
class Person {
String name;
Person(this.name); // Constructor
void showName() {
print("Name: $name");
}
}
Here, the constructor initializes the name when an object is created.

9. What is method overriding in Dart?


Method Overriding in Dart occurs when a subclass (child class) provides its own version of a
method that is already defined in the superclass (parent class). This allows the child class to
change or extend the behavior of the inherited method.
To override a method, Dart uses the @override annotation.
Example:
class Animal {
void sound() {
print("Animal sound");
}
}
class Dog extends Animal {
@override
void sound() {
print("Dog barks");
}
}

4 Marks Questions
1. Discuss the importance of Dart in modern application development.
Dart is very important in modern app development because it allows developers to build
apps for multiple platforms like Android, iOS, web, and desktop using a single codebase,
especially with the Flutter framework.
Key points:
• Dart is the main language for Flutter, which is popular for making beautiful and fast
apps.
• It supports hot reload, which helps developers see changes instantly while building
apps.
• Dart has a clean and simple syntax, making it easy to learn and use.
• It supports both object-oriented programming and functional style, which gives
developers flexibility.
Because of these features, Dart helps in faster development, code reusability, and reduces
the effort of writing different code for different platforms.

2. What are the advantages of using Dart for application development?


Here are the main advantages of using Dart:
1. Cross-Platform Development: Dart with Flutter allows you to write one code that runs
on Android, iOS, web, and desktop.
2. Fast Development: Dart supports hot reload, so developers can quickly test and fix
issues.
3. Strong Typing: Dart is a typed language, which means fewer bugs and more reliable
code.
4. High Performance: Dart compiles to native code (AOT), which means faster and
smoother apps.
5. Object-Oriented: Dart supports object-oriented concepts like classes, objects, and
inheritance, which helps organize code better.
Because of these benefits, Dart is widely used for modern and scalable application
development.

3. Explain the concept of decision-making in Dart with an example.


Decision-making in Dart means making choices in a program based on certain conditions.
Dart uses if, else if, and else statements for decision-making.
Example:
void main() {
int marks = 85;
if (marks >= 90) {
print("Grade A");
} else if (marks >= 75) {
print("Grade B");
} else {
print("Grade C");
}
}
Explanation:
• If marks is 90 or more, it prints "Grade A".
• If marks is 75 to 89, it prints "Grade B".
• Otherwise, it prints "Grade C".
This helps the program choose the right path depending on the situation.

4. Describe the different data types available in Dart.


Dart supports many data types to handle different types of values. Some commonly used
data types are:
1. int – For whole numbers.
Example: int age = 20;
2. double – For decimal numbers.
Example: double price = 99.99;
3. String – For a sequence of characters (text).
Example: String name = "Vishva";
4. bool – For true or false values.
Example: bool isLoggedIn = true;
5. List – For storing multiple values in a single variable (like an array).
Example: List<String> fruits = ["Apple", "Banana"];
6. Map – For key-value pairs.
Example: Map<String, int> marks = {"Math": 90, "English": 85};
5. What are lists in Dart? Provide an example of how to create and manipulate a list.
In Dart, a List is a collection of ordered elements, just like arrays in other programming
languages. Lists are used when you want to store multiple values in a single variable.

✦ Types of Lists:
• Growable List (default): Size can change (add/remove items).
• Fixed-length List: Size is fixed at creation, cannot be changed.

✦ Common operations:
• add() – adds a new item
• remove() – removes item by value
• insert() – adds item at a specific index
• length – returns number of items
• [] – access or modify items

✦ Example:
void main() {
List<String> fruits = ["Apple", "Banana", "Mango"];
fruits.add("Orange"); // Add item
fruits[1] = "Grapes"; // Update item at index 1
fruits.remove("Apple"); // Remove item
print(fruits); // Output: [Grapes, Mango, Orange]
}

✦ Importance:
Lists make it easy to manage groups of data like names, marks, items, etc., in a structured
and flexible way.

6. Explain the concept of getter and setter in Dart with an example.


In Dart, getters and setters are special methods used to get and set the values of private
variables (variables starting with _). They help in encapsulating the data and controlling how
data is accessed or changed.

✦ Getter:
Used to retrieve (get) the value of a variable.

✦ Setter:
Used to set (update) the value of a variable.
✦ Why use them?
• To hide internal data (encapsulation).
• To control access or apply conditions when changing a value.

✦ Example:
class Student {
String _name = "";
String get name => _name; // getter
set name(String value) => _name = value; // setter
}
void main() {
var s = Student();
s.name = "Ravi"; // using setter
print(s.name); // using getter
}

✦ Output:
Ravi
This ensures secure and controlled access to class variables.

7. What is an abstract class in Dart? How does it differ from a regular class?
An abstract class in Dart is a class that cannot be directly used to create objects. It is meant
to be extended (inherited) by other classes. It can contain abstract methods (without body)
and normal methods (with body).

✦ Main purpose:
To create a base class for other classes to follow a common structure.

✦ Difference from regular class:


Abstract Class Regular Class

Cannot be instantiated Can be instantiated

May have unimplemented methods All methods must be implemented

Used to define structure Used to define full behavior

✦ Example:
abstract class Animal {
void sound(); // abstract method
void eat() {
print("Animal eats");
}
}
class Dog extends Animal {
@override
void sound() {
print("Dog barks");
}
}
Here, Animal is abstract and defines the structure. Dog implements the missing method.

8. Describe the concept of inheritance in Dart with an example.


Inheritance is an object-oriented programming concept where a class (child) can inherit
properties and methods from another class (parent).

✦ Why use inheritance?


• Code reusability: Common features can be shared.
• Extensibility: You can add extra features in child class.
• Organization: Helps group related classes.
✦ Keywords:
• extends is used to inherit a class.

✦ Example:
class Animal {
void eat() {
print("Animal eats");
}
}
class Dog extends Animal {
void bark() {
print("Dog barks");
}
}
void main() {
Dog d = Dog();
d.eat(); // from Animal
d.bark(); // from Dog
}

✦ Output:
Animal eats
Dog barks
The child class can use the methods of the parent class and also have its own methods.

9. What is polymorphism in Dart? Provide an example to illustrate your answer.


Polymorphism means "many forms". It allows one method to behave differently based on
the object calling it. In Dart, polymorphism is mainly achieved through method overriding
using inheritance.
✦ Why use it?
• For flexibility in code
• Allows us to write generic functions that work on different objects

✦ Example:
class Animal {
void sound() {
print("Animal makes a sound");
}
}
class Dog extends Animal {
@override
void sound() {
print("Dog barks");
}
}
class Cat extends Animal {
@override
void sound() {
print("Cat meows");
}
}
void main() {
Animal a;
a = Dog();
a.sound(); // Dog barks
a = Cat();
a.sound(); // Cat meows
}

✦ Output:
Dog barks
Cat meows
This is runtime polymorphism – the method behaves differently depending on the object
type.

6 Marks Questions
1. Discuss the benefits of using Dart for application development, particularly in mobile
and web applications.
Dart is a modern, object-oriented programming language developed by Google. It is widely
used for building mobile, web, and desktop applications, especially when used with Flutter.

Benefits of Dart in Mobile and Web App Development:


1. Cross-Platform Development:
o Dart allows developers to write a single codebase that runs on Android, iOS,
Web, Desktop, and more.
o Saves time and effort as you don’t need to write separate code for each
platform.
2. Fast Development with Hot Reload:
o Dart supports hot reload, especially in Flutter, which means changes in code
can be seen immediately.
o This helps developers fix bugs and test features quickly.
3. Simple and Easy Syntax:
o Dart has a clean and familiar syntax similar to Java, C++, and JavaScript, which
makes it easier to learn and use.
4. High Performance:
o Dart can be compiled to native machine code, which makes apps run faster.
o It also compiles to JavaScript for web applications.
5. Strong Typing and Safety:
o Dart is a type-safe language, which helps catch errors at compile time.
o Supports null safety to avoid common bugs like null pointer exceptions.
6. Rich Standard Library:
o Dart offers a large set of built-in libraries for math, collections, file handling,
and web programming.
7. Good Tooling Support:
o Works well with IDEs like VS Code and Android Studio.
o Provides tools for debugging, testing, formatting, etc.
8. Backed by Google:
o Dart and Flutter are supported and regularly updated by Google, ensuring long-
term use and reliability.

2. Discuss the importance of Dart in Flutter Development.


Flutter is a UI framework developed by Google, and Dart is the official programming
language used to build Flutter applications.

Why Dart is important in Flutter:


1. Designed for UI:
o Dart was specially designed to build modern user interfaces. It supports
widgets, custom components, and animations, which are key features in
Flutter.
2. Fast Performance:
o Dart can compile into native ARM code, which helps Flutter apps run smoothly
and quickly on both Android and iOS.
3. Hot Reload:
o Dart supports hot reload, allowing developers to instantly see changes in their
code without restarting the whole app.
4. Single Language for All Platforms:
o Developers can use Dart to create apps for mobile, web, desktop, and
embedded devices using the same Flutter codebase.
5. Object-Oriented and Class-Based:
o Dart supports classes, inheritance, and polymorphism, making it suitable for
building large and complex apps.
6. Null Safety:
o Dart includes null safety, helping developers avoid common programming
errors and make code more reliable.
7. Strong Community and Support:
o Dart has a growing developer community and is actively maintained by Google,
making it a safe and stable choice.

3. Explain the concept of loops in Dart. Provide examples of different types of loops
available in Dart.
In Dart, loops are used to repeat a block of code multiple times. They help perform tasks like
printing numbers, processing lists, or waiting for input without writing the same code again
and again.

Types of Loops in Dart:

1. for Loop
Used when you know how many times you want to repeat the code.
void main() {
for (int i = 1; i <= 5; i++) {
print("Number: $i");
}
}
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

2. while Loop
Used when you want to run the loop as long as a condition is true.
void main() {
int i = 1;
while (i <= 3) {
print("Hello $i");
i++;
}
}
Output:
Hello 1
Hello 2
Hello 3

3. do-while Loop
This loop runs the code at least once, even if the condition is false initially.
void main() {
int i = 1;
do {
print("Hi $i");
i++;
} while (i <= 2);
}
Output:
Hi 1
Hi 2

4. for-in Loop
Used to loop through elements in a collection, like a list.
void main() {
List<String> fruits = ["Apple", "Banana", "Mango"];
for (var fruit in fruits) {
print(fruit);
}
}
Output:
Apple
Banana
Mango

5. break and continue:


• break: Stops the loop early.
• continue: Skips the current iteration.
for (int i = 1; i <= 5; i++) {
if (i == 3) continue;
print(i);
}
Output:
1
2
4
5
4. Write a Dart program that demonstrates the use of a class, object, and constructor.
A class is a blueprint to create objects. A constructor is a special method used to initialize
the object when it is created.

Dart Program Example:


class Student {
String name;
int age;
// Constructor
Student(String n, int a) {
name = n;
age = a;
}
void display() {
print("Name: $name");
print("Age: $age");
}
}
void main() {
// Creating an object of Student
Student s1 = Student("Ravi", 20);
s1.display();
}
Output:
Name: Ravi
Age: 20

5. Explain the concept of anonymous functions in Dart and provide an example of how
they can be used.
An anonymous function in Dart is a function without a name. These are also called lambda
functions or inline functions.

Why use them?


• To write short functions.
• To pass functions as arguments to other functions.
• Useful in loops, lists, and callbacks.

Example:
void main() {
// Anonymous function assigned to a variable
var greet = () {
print("Hello from anonymous function");
};
greet();
// Anonymous function in list forEach
List names = ["Amit", "Neha", "Ravi"];
names.forEach((name) {
print("Hi $name");
});
}

Output:
Hello from anonymous function
Hi Amit
Hi Neha
Hi Ravi

6. Discuss the use of named parameters in Dart functions. Provide an example to illustrate
your answer.
In Dart, named parameters allow you to pass arguments by name instead of by position.
They are useful for clarity and optional parameters.

Syntax:
void functionName({type param1, type param2}) { }

Benefits:
• Increases readability
• Allows default values
• Makes parameters optional

Example:
void greet({String name = "Guest", int age = 0}) {
print("Hello $name, you are $age years old.");
}
void main() {
greet(name: "Ravi", age: 25);
greet(); // uses default values
}

Output:
Hello Ravi, you are 25 years old.
Hello Guest, you are 0 years old.
7. Explain the concept of HashMap in Dart. How does it differ from a List? Provide
examples of both.
A HashMap is a collection of key-value pairs. It is also known as a Map in Dart. It stores data
using unique keys, which makes it easy to search and manage data.

Difference between HashMap and List:

Feature HashMap (Map) List

Data Format Key-Value pairs Ordered collection of values

Access By key By index

Uniqueness Keys must be unique Values can repeat

Example of HashMap:
void main() {
Map<String, String> capitals = {
"India": "New Delhi",
"USA": "Washington",
"Japan": "Tokyo"
};
print(capitals["India"]); // Output: New Delhi
}

Example of List:
void main() {
List<String> countries = ["India", "USA", "Japan"];
print(countries[0]); // Output: India
}

8. Describe the concept of interfaces in Dart. How do you implement an interface in a


class?
In Dart, every class can act as an interface. An interface is used to define what a class must
do, but not how it does it.
You implement an interface using the implements keyword and must override all the
methods of the interface.

Why use interfaces?


• To create common behavior across different classes.
• Supports multiple inheritance.

Example:
class Printable {
void printData(); // interface method
}
class Book implements Printable {
@override
void printData() {
print("Printing book details...");
}
}
void main() {
Book b = Book();
b.printData();
}

Output:
Printing book details...

9. Write a Dart program that demonstrates method overriding and polymorphism using a
base class and derived classes.
Polymorphism means using the same method but having different behavior depending on
the object. This is done using method overriding.

Dart Program:
class Animal {
void makeSound() {
print("Animal makes a sound");
}
}
class Dog extends Animal {
@override
void makeSound() {
print("Dog barks");
}
}
class Cat extends Animal {
@override
void makeSound() {
print("Cat meows");
}
}
void main() {
Animal a;
a = Dog();
a.makeSound(); // Dog barks
a = Cat();
a.makeSound(); // Cat meows
}

Output:
Dog barks
Cat meows
Unit-2 Introduction to Flutter
2 Marks Questions
1. What is Flutter?
Flutter is an open-source framework developed by Google for building beautiful, fast, and
cross-platform mobile, web, and desktop applications using a single codebase.
• It uses the Dart programming language.
• Apps built with Flutter work on Android, iOS, Web, and Desktop.
• Flutter allows creating apps with smooth performance and a rich user interface using
widgets.

Example: You can use Flutter to make apps like calculators, shopping apps, or chat apps.

2. What is the purpose of the main.dart file in a Flutter application?


The main.dart file is the entry point of every Flutter application.
• It contains the main() function, which is the starting point of the app.
• It usually includes the MaterialApp and the first screen (widget) of the app.
• All other files and widgets are connected through this file.

3. What is the difference between Stateless and Stateful widgets in Flutter?

Feature StatelessWidget StatefulWidget

Change in UI Can’t change after build Can change when state changes

Data or state Fixed (constant) Dynamic (can change)

Example use Static UI like labels, icons Counters, form inputs, etc.

• StatelessWidget is used when the UI doesn’t need to change.


• StatefulWidget is used when the UI updates or responds to user actions.

Example:
• Use Stateless for displaying a title.
• Use Stateful for a like button that changes color when clicked.

4. What is the role of the Container widget in Flutter?


The Container widget in Flutter is a box model used for:
• Adding padding, margin, color, size, and alignment to its child.
• It helps in designing and decorating parts of the UI.
• It can hold one child widget and apply style to it.

Example: You can wrap a Text widget in a Container to give it background color and
space.
Container(
padding: EdgeInsets.all(10),
color: Colors.blue,
child: Text("Hello"),
);

5. What is the purpose of the MaterialApp class in Flutter?


MaterialApp is the root widget of a Flutter app that follows Material Design.
• It provides the basic structure and style for the app, like themes, colors, fonts,
navigation, and routing.
• It also helps manage the home screen and routes (pages).

Think of MaterialApp as the setup for the entire app – it tells Flutter how your app should
look and behave.
void main() {
runApp(MaterialApp(
home: MyHomePage(),
));
}
4 Marks Questions
1. Explain the architecture of Flutter.
Flutter architecture is made up of three main layers:

1. Framework Layer
• Written in Dart.
• Provides the structure for creating UI using widgets (Stateless & Stateful).
• Contains Material and Cupertino libraries for Android and iOS design.

2. Engine Layer
• Written in C++.
• Handles low-level things like graphics (Skia engine), text rendering, layout, and Dart
runtime.

3. Embedder Layer
• Platform-specific code written in languages like Java (Android), Objective-C/Swift
(iOS).
• Acts as a bridge between the Flutter engine and the device.

2. Write a short Flutter code to display “Hello, Flutter!”.


Here is a simple Flutter app that shows the message on screen:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text("My First App")),
body: Center(child: Text("Hello, Flutter!")),
),
);
}
}

3. Write and explain a Flutter program that uses a Stateless Widget to display a column of
text.

Flutter Code:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text("Stateless Example")),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("Line 1"),
Text("Line 2"),
Text("Line 3"),
],
),
),
);
}
}

4. Describe the steps to install Flutter on macOS.

Step-by-step Installation on macOS:


1. Download Flutter SDK
o Go to https://flutter.dev and download the macOS version of Flutter.
2. Extract the ZIP file
o Extract it to a folder like ~/development/flutter.
3. Set Flutter Path
o Open Terminal and run:
export PATH="$PATH:`pwd`/flutter/bin"
o Add this to your .zshrc or .bash_profile file for permanent use.
4. Check Installation
o Run:
flutter doctor
o It shows missing dependencies (like Xcode, Android Studio).
5. Install Xcode (from App Store)
o Needed for iOS development.
6. Install Android Studio
o For Android emulator and SDK tools.

5. How do you create and run a Flutter application in a web browser?


Steps to Create & Run Flutter App in Web:
1. Enable Web Support
o Make sure you have Flutter 2.0 or above installed.
o Run:
flutter devices
2. Create a Flutter Project
o Run:
flutter create my_web_app
cd my_web_app
3. Run the App in Browser
o Use this command:
flutter run -d chrome
4. OR Build a Web App
o Run:
flutter build web
o Output is stored in build/web/ folder.

6. What is the Scaffold widget, and what are its main components?
Scaffold is a Flutter widget that provides a basic structure and layout for a visual app.

Common components inside Scaffold:


• appBar: Displays a top bar (title, icons).
• body: Main content area of the screen.
• floatingActionButton: A round button usually for quick actions.
• drawer: A side menu panel.
• bottomNavigationBar: A menu bar at the bottom.

Example:
Scaffold(
appBar: AppBar(title: Text("My App")),
body: Center(child: Text("Hello")),
floatingActionButton: FloatingActionButton(
onPressed: () {},
child: Icon(Icons.add),
),
);

Scaffold helps organize your screen with proper layout, navigation, and actions.

7. How can you add decoration to a Container widget in Flutter? Provide an example.
You can add decoration to a Container using the decoration: property with a BoxDecoration.

Features of BoxDecoration:
• color: background color
• border: border style
• borderRadius: rounded corners
• boxShadow: shadow effect
• image: background image

Example:
Container(
width: 200,
height: 100,
decoration: BoxDecoration(
color: Colors.blue,
borderRadius: BorderRadius.circular(15),
border: Border.all(color: Colors.black, width: 2),
boxShadow: [
BoxShadow(color: Colors.grey, blurRadius: 5, offset: Offset(2, 2)),
],
),
child: Center(child: Text("Decorated Box", style: TextStyle(color: Colors.white))),
)

6 Marks Questions
1. Discuss the differences between Stateless and Stateful widgets in detail, including when
to use each type.

Feature Stateless Widget Stateful Widget

UI update Can’t change once built Can change based on user interaction

State/data Fixed/static Dynamic, can be updated

Lifecycle methods Simple lifecycle Has initState(), setState(), etc.

Example use Text, logo, static screen Forms, toggle switch, counter app

Use StatelessWidget when:


• The screen does not need to update.
• Example: Home screen title, static content.

Use StatefulWidget when:


• UI needs to respond to user input or change dynamically.
• Example: Like button, form validation, live counter.

2. Compare Flutter with other mobile development frameworks like React Native or
Xamarin.

Feature Flutter React Native Xamarin

Language Dart JavaScript C#

UI rendering Uses own widgets Uses native components Uses native UI


Feature Flutter React Native Xamarin

Very high Good (bridge slows down


Performance High (compiled)
(compiled) sometimes)

Community Growing Very large Moderate

Needs Visual
Setup Easy to set up Also easy
Studio

Codebase
Full cross-platform High High
sharing

Flutter’s Advantages:
• Fast UI building with widgets.
• Hot reload for quick testing.
• Excellent for both Android and iOS.

3. Explain how to apply styles and themes in a Flutter application. Provide examples of
how to use themes effectively.
Flutter allows you to define themes for the whole app using ThemeData. This makes your
app look consistent and easy to style.

Applying Theme:
MaterialApp(
theme: ThemeData(
primaryColor: Colors.blue,
textTheme: TextTheme(
bodyLarge: TextStyle(fontSize: 18, color: Colors.black),
),
),
home: MyHomePage(),
);
Using the theme inside widgets:
Text("Hello", style: Theme.of(context).textTheme.bodyLarge);

Benefits:
• You can change the whole app's style from one place.
• Helps in maintaining dark/light mode, consistent colors, fonts, and text sizes.

4. Describe the structure and components of a typical Flutter application, including the
role of the AppBar and Center widgets.
A basic Flutter app structure includes:

Main Components:
• main(): Entry point of the app.
• MaterialApp: Root of the app, sets up theme and navigation.
• Scaffold: Provides layout structure like app bar, body, etc.
• AppBar: Top navigation bar with title and actions.
• Center: Centers a child widget on the screen.

Example Structure:
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text("My App")),
body: Center(child: Text("Welcome")),
),
);
}
}
AppBar: shows title/navigation
Center: aligns content in the center

5. Illustrate the process of creating a simple Flutter application that includes a Container
with decoration, an AppBar, and a Center widget. Include code snippets.

Simple Flutter App Example:


import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text("Decorated Box")),
body: Center(
child: Container(
width: 200,
height: 100,
decoration: BoxDecoration(
color: Colors.orange,
borderRadius: BorderRadius.circular(15),
boxShadow: [
BoxShadow(
color: Colors.grey,
blurRadius: 10,
offset: Offset(4, 4),
),
],
),
child: Center(child: Text("Hello Container")),
),
),
),
);
}
}

6. Discuss the importance of the MaterialApp class in Flutter and how it contributes to the
overall app structure and navigation.
MaterialApp is a core widget that wraps the whole Flutter app and follows Material Design.

Key Features:
• Sets the theme and default styling.
• Provides navigation system (routes, named routes).
• Manages localization, title, font, and more.

Example:
MaterialApp(
title: "My App",
theme: ThemeData(primarySwatch: Colors.teal),
home: HomePage(),
);

Contributions:
• Helps maintain a consistent look across the app.
• Makes navigation between screens easy.
• Defines initial screen of the app (home:).
• Supports dark/light themes and global styles.
Unit-3 Widgets in Flutter
2 Marks Questions
1. What is the purpose of the Text widget in Flutter?
The Text widget in Flutter is used to display a string of text on the screen.
• You can show labels, titles, messages, etc.
• It also allows customization like changing font size, color, alignment, and style.

Example:
Text("Welcome to Flutter")

2. How can you add padding to a Text widget?


To add padding (space inside a widget), wrap the Text widget with a Padding widget.

Example:
Padding(
padding: EdgeInsets.all(16.0),
child: Text("Padded Text"),
)
• EdgeInsets.all(16.0) adds 16 pixels of space on all sides of the text.

3. What is the function of the Icon widget in Flutter?


The Icon widget is used to display icons (like a star, heart, phone, etc.) from Flutter's built-in
icon sets.
• Icons are useful for buttons, navigation bars, and actions.

Example:
Icon(Icons.home, size: 30, color: Colors.blue)

4. What is the difference between padding and margin in Flutter?


Feature Padding Margin

Space inside a widget (around its Space outside a widget (around its
Meaning
content) border)

Use Pushes content inward Pushes widget away from others

Widget
Padding widget Use inside Container with margin:
used

Example:
// Padding
Padding(
padding: EdgeInsets.all(10),
child: Text("Inside Padding"),
)
// Margin
Container(
margin: EdgeInsets.all(10),
child: Text("Outside Margin"),
)

5. What is the role of the Expanded widget in a Flutter layout?


The Expanded widget is used inside Row or Column to take up available space.
• It stretches the child widget to fill the remaining space.
• Useful for making responsive layouts.

Example:
Row(
children: [
Expanded(child: Text("Left")),
Expanded(child: Text("Right")),
],
)

4 Marks Questions
1. Explain how to add a custom font to a Flutter application.
To use a custom font in Flutter:

Step-by-step process:
1. Download the font (like .ttf) and add it to a folder (e.g., assets/fonts/).
2. Update pubspec.yaml:
flutter:
fonts:
- family: MyFont
fonts:
- asset: assets/fonts/MyFont.ttf
3. Use the font in your Text widget:
Text(
"Hello",
style: TextStyle(fontFamily: 'MyFont'),
)

Now your app will display text using your custom font!

2. Describe the different types of buttons available in Flutter. Provide examples of at least
two types.
Flutter provides many button widgets to perform actions:

Common types:
1. ElevatedButton – Raised look, for primary actions.
ElevatedButton(
onPressed: () {},
child: Text("Click Me"),
)
2. TextButton – Flat text-style button, often used for links.
TextButton(
onPressed: () {},
child: Text("Forgot Password?"),
)
3. OutlinedButton – Border-only button, no fill color.
4. IconButton – Only shows an icon, no text.
5. FloatingActionButton – Circular button, used for main action.

3. How do you add an image to a Flutter application? Include code snippets.

To add an image:
1. Place your image in a folder (e.g., assets/images/).
2. Add it to pubspec.yaml:
flutter:
assets:
- assets/images/pic.png
3. Use the image in your app:
Image.asset("assets/images/pic.png")

You can also load images from the internet:


Image.network("https://example.com/photo.jpg")

4. Discuss the use of Rows and Columns in Flutter for layout design.
• Row and Column are used to arrange widgets in horizontal and vertical directions.

Row:
• Displays widgets side by side.
Row(
children: [
Icon(Icons.star),
Text("Stars"),
],
)

Column:
• Displays widgets one below the other.
Column(
children: [
Text("Hello"),
Text("Flutter"),
],
)

Benefits:
• Helps in building clean and flexible UI layouts.
• Can be combined with other widgets like Expanded, Center, or Container.

5. What is the Inkwell widget, and how does it enhance user interaction in Flutter
applications?
• InkWell is a ripple effect widget.
• It detects touch gestures like taps, and shows a ripple animation when clicked.

Use case:
To make any widget (like Container or Text) respond to a tap.
Example:
InkWell(
onTap: () {
print("Tapped!");
},
child: Container(
padding: EdgeInsets.all(10),
color: Colors.blue,
child: Text("Tap Me"),
),
)6. Compare Container, Padding, and SizedBox widgets with example.
In Flutter, Container, Padding, and SizedBox are layout widgets used to design spacing and
structure of the user interface. Each has a specific role.

Feature /
Container Padding SizedBox
Widget

Used to add space


Used to create empty
Used to wrap, style, size, inside a widget
Purpose space or give fixed
and position a child widget (between its border and
width/height to a widget
content)

Can hold Yes (optional, can be


Yes Yes
child? empty)

Supports Yes (color, border, No styling, only


No styling, only sizing
styling? radius, margin, etc.) spacing

Controls both internal and


Space Controls only internal
external spacing using Controls fixed space only
Control spacing
padding and margin
Feature /
Container Padding SizedBox
Widget

Designing box-style UI, Adding spacing around Adding gaps between


Best for backgrounds, borders, and content inside another widgets or setting a fixed
layout widget size

Examples

Container Example:
Container(
width: 100,
height: 100,
color: Colors.red,
child: Text("Box"),
)

Padding Example:
Padding(
padding: EdgeInsets.all(10),
child: Text("Padded Text"),
)

SizedBox Example:
SizedBox(height: 20), // Adds vertical space

6 Marks Questions
1. Explain the concept of ScrollView in Flutter and describe its different types, including
use cases for each.

What is ScrollView?
In Flutter, ScrollView is a widget that allows content to scroll vertically or horizontally,
especially when the content is too large to fit on the screen.

Types of ScrollViews:

ScrollView Type Use Case Description

When you have one long child (e.g., Scrolls a single widget (like a
SingleChildScrollView
Column) that needs scrolling Column or Row)

When you want to display a Automatically scrolls and


ListView
scrollable list of items reuses widgets efficiently

When you want to show items in a Useful for image galleries,


GridView
grid format (rows and columns) product lists

When you want to create complex Used with Slivers for custom
CustomScrollView
scroll effects scroll layouts

2. Discuss the Drawer widget in Flutter, including how to implement it and its typical
use cases in an application.

What is Drawer?
The Drawer widget in Flutter is a side panel that slides in from the left (or right) of the
screen. It is used for app navigation, like showing links to pages, settings, profile, etc.

Use Cases:
• Navigation menus
• User profile access
• App settings

How to Use:
Scaffold(
appBar: AppBar(title: Text("My App")),
drawer: Drawer(
child: ListView(
children: [
DrawerHeader(
child: Text("Menu"),
decoration: BoxDecoration(color: Colors.blue),
),
ListTile(title: Text("Home")),
ListTile(title: Text("Settings")),
],
),
),
)

3. Illustrate how to create a ListView in Flutter, including the use of ListTile for displaying
items. Provide a code example.

ListView:
ListView is a scrollable list of widgets. It is perfect for dynamic or long lists.

ListTile:
ListTile is a ready-to-use widget for displaying title, subtitle, icons, and trailing info in a list
item.

Example:
ListView(
children: [
ListTile(
leading: Icon(Icons.person),
title: Text("John Doe"),
subtitle: Text("Developer"),
trailing: Icon(Icons.arrow_forward),
),
ListTile(
leading: Icon(Icons.person),
title: Text("Jane Smith"),
subtitle: Text("Designer"),
),
],
)

4. Describe the Card widget in Flutter and how it can be used to create visually appealing
UI components. Include an example.

What is Card?
The Card widget in Flutter is used to group content in a box with rounded corners and
elevation (shadow). It helps in creating clean and modern UI designs.

Use Cases:
• Displaying user profiles
• Product cards
• News headlines

Example:
Card(
elevation: 4,
margin: EdgeInsets.all(10),
child: ListTile(
leading: Icon(Icons.email),
title: Text("Email"),
subtitle: Text("example@gmail.com"),
),
)

5. Explain the purpose of the Wrap widget in Flutter and how it differs from Row and
Column. Provide an example of its usage.

What is Wrap?
The Wrap widget arranges widgets horizontally or vertically and automatically moves them
to the next line when there’s no space.

Difference from Row & Column:

Widget Behavior

Row Puts items in a straight line horizontally. No wrap.

Column Puts items in a straight line vertically. No wrap.

Wrap Wraps items to next row/column when space runs out.

Example:
Wrap(
spacing: 10,
runSpacing: 10,
children: [
Chip(label: Text("Flutter")),
Chip(label: Text("Dart")),
Chip(label: Text("Android")),
Chip(label: Text("Web")),
],
)
Unit-4 UI Components
2 Marks Questions
1. What is a Carousel Slider in Flutter?
A Carousel Slider in Flutter is a widget that lets you show images or content in a sliding
banner format. It automatically slides to the next item and is used in many apps like e-
commerce, news, or photo galleries.

Example Use:
• Displaying a slideshow of product images.
• Showing promotional banners on a homepage.

Example Code:
CarouselSlider(
items: [Image.asset('img1.jpg'), Image.asset('img2.jpg')],
options: CarouselOptions(autoPlay: true),
)

2. How do you create tabs in a Flutter application?


To create tabs in Flutter, you use the TabBar (for the tab menu) and TabBarView (for the
content). It allows you to switch between different screens in the same page.

Steps:
1. Wrap your widgets in a DefaultTabController.
2. Add TabBar and TabBarView.

Example Code:
DefaultTabController(
length: 2,
child: Scaffold(
appBar: AppBar(
bottom: TabBar(tabs: [Tab(text: "Home"), Tab(text: "Settings")]),
),
body: TabBarView(children: [Text("Home Page"), Text("Settings Page")]),
),
)

3. What is the purpose of the ExpansionTile widget in Flutter?


ExpansionTile is a widget that shows a title, and when clicked, expands to show more
content. It helps to hide and show details when needed, keeping the UI clean.

Use Cases:
• FAQ sections
• List of expandable settings

Example:
ExpansionTile(
title: Text("More Info"),
children: [Text("Here is the detailed information.")],
)

4. What is the difference between a Circular and Linear ProgressBar in Flutter?

Type Description

CircularProgressIndicator Shows progress in a circular shape, usually for loading screens.

LinearProgressIndicator Shows progress in a horizontal bar, like a loading bar.

Example:
CircularProgressIndicator() // Circular loader
LinearProgressIndicator() // Horizontal bar loader
Both show loading animations but in different shapes.
5. What is the function of the ConvexBottomBar in Flutter?
The ConvexBottomBar is a stylish bottom navigation bar in Flutter that has a curved
(convex) shape in the middle. It is used to navigate between different pages in the app and
looks more modern than the regular bottom bar.

Features:
• Beautiful design with animation
• Easy to use with icons and labels

Example:
ConvexAppBar(
items: [
TabItem(icon: Icons.home, title: 'Home'),
TabItem(icon: Icons.person, title: 'Profile'),
],
initialActiveIndex: 0,
onTap: (int i) => print('click index=$i'),
)

4 Marks Questions
1. Explain how to implement a horizontal list in Flutter. Provide an example.
A horizontal list is used when you want to scroll items from left to right instead of top to
bottom.

Use Case:
• Showing product cards
• Image galleries
• Category selection

How to Create:
Use ListView with scrollDirection: Axis.horizontal.

Example:
SizedBox(
height: 100,
child: ListView(
scrollDirection: Axis.horizontal,
children: [
Container(width: 100, color: Colors.red),
Container(width: 100, color: Colors.green),
Container(width: 100, color: Colors.blue),
],
),
)

2. Describe how to create and use a dialog box in Flutter. What are the different types of
dialog boxes available?
A dialog box is a small popup that gives a message, alert, or gets input from the user.

Use Case:
• Alerts
• Confirmations
• Input forms

Types of Dialogs:
• AlertDialog – for messages and actions (OK/Cancel)
• SimpleDialog – for selecting options
• Dialog – base class for custom dialogs
• showModalBottomSheet() – for sliding-up panels

Example (AlertDialog):
showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text("Confirm"),
content: Text("Do you want to exit?"),
actions: [
TextButton(onPressed: () => Navigator.pop(context), child: Text("Cancel")),
TextButton(onPressed: () => exit(0), child: Text("Yes")),
],
);
},
);

3. How can you create a Staggered GridView in Flutter? Discuss its use cases.
A Staggered GridView is a type of layout where items have different heights or sizes, like
Pinterest layout.

Use Case:
• Photo galleries
• Masonry layouts
• Product or blog cards

How to Use:
You need to use the flutter_staggered_grid_view package.

Example:
# pubspec.yaml
dependencies:
flutter_staggered_grid_view: ^0.6.1
StaggeredGrid.count(
crossAxisCount: 4,
children: [
StaggeredGridTile.count(
crossAxisCellCount: 2,
mainAxisCellCount: 2,
child: Container(color: Colors.red),
),
StaggeredGridTile.count(
crossAxisCellCount: 2,
mainAxisCellCount: 1,
child: Container(color: Colors.green),
),
],
)

4. Illustrate how to create an analog clock in Flutter. Include code snippets.


An analog clock shows time using hands like a traditional wall clock. You can use
CustomPaint and Timer.

Use Case:
• Clock apps
• Dashboards
• Learning projects

Example (Basic Idea):


class AnalogClock extends StatefulWidget {
@override
_AnalogClockState createState() => _AnalogClockState();
}
class _AnalogClockState extends State<AnalogClock> {
late Timer _timer;
DateTime _dateTime = DateTime.now();
@override
void initState() {
_timer = Timer.periodic(Duration(seconds: 1), (_) {
setState(() {
_dateTime = DateTime.now();
});
});
super.initState();
}
@override
Widget build(BuildContext context) {
return CustomPaint(
painter: ClockPainter(_dateTime),
size: Size(200, 200),
);
}
}

5. Discuss how to work with charts in Flutter. What libraries can be used for this purpose?
To display charts like bar, pie, and line charts, Flutter provides chart libraries.

Use Cases:
• Display sales data
• Show analytics
• Visualize reports
Popular Chart Libraries:
1. charts_flutter – Google-maintained, good for bar, pie, line charts
2. fl_chart – Modern UI, supports customizations and animations
3. syncfusion_flutter_charts – Feature-rich, free for learning

Example using fl_chart:


# pubspec.yaml
dependencies:
fl_chart: ^0.40.0
dart
CopyEdit
BarChart(
BarChartData(
barGroups: [
BarChartGroupData(x: 0, barRods: [BarChartRodData(toY: 10)]),
BarChartGroupData(x: 1, barRods: [BarChartRodData(toY: 12)]),
],
),
)

6 Marks Questions
1. Explain the process of handling videos in a Flutter application. What packages are
commonly used, and how do you implement video playback?
To play videos in a Flutter app, we commonly use the video_player package.
Steps:
1. Add the video_player package in pubspec.yaml.
2. Import the package in the Dart file.
3. Create a VideoPlayerController to load the video.
4. Use VideoPlayer widget to show the video.
5. Use controller.play() to play and controller.pause() to pause.
Example:
VideoPlayerController _controller = VideoPlayerController.asset('assets/video.mp4')
..initialize().then((_) {
setState(() {});
});
VideoPlayer(_controller)
Other Packages:
• chewie (adds better controls on top of video_player)
• better_player (for more features)

2. Discuss the implementation of the ExpansionTile and Card widgets together to create an
expandable list. Provide a code example.
ExpansionTile is used to expand/collapse a section. When used with Card, it looks more
beautiful.
Steps:
1. Wrap ExpansionTile inside a Card.
2. Put data in the title and expanded content in children.
Example:
ListView(
children: [
Card(
child: ExpansionTile(
title: Text("Student Name"),
children: [Text("Details: Roll no, Grade")],
),
),
],
)
Use:
• FAQ sections
• Showing summary and details

3. Describe the steps to create a custom dialog in Flutter, including how to handle user
input and actions.
A custom dialog is used to take input or show special content.
Steps:
1. Use showDialog() function.
2. Return an AlertDialog or custom Dialog.
3. Add TextField or buttons for user input.
4. Handle input with TextEditingController.
Example:
showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text("Enter Name"),
content: TextField(controller: _nameController),
actions: [
TextButton(onPressed: () => Navigator.pop(context), child: Text("Cancel")),
TextButton(onPressed: () {
print(_nameController.text);
Navigator.pop(context);
}, child: Text("Submit")),
],
);
},
);

4. Illustrate the use of the StaggeredGridView widget in Flutter, including its advantages
over a regular GridView. Provide a code example.
StaggeredGridView is like a GridView but allows items of different heights and widths.
Advantages:
• Looks more natural and beautiful
• Good for image galleries, Pinterest-style layouts
Package Used:
• flutter_staggered_grid_view
Example:
StaggeredGrid.count(
crossAxisCount: 4,
children: [
StaggeredGridTile.count(
crossAxisCellCount: 2,
mainAxisCellCount: 2,
child: Container(color: Colors.red),
),
StaggeredGridTile.count(
crossAxisCellCount: 2,
mainAxisCellCount: 1,
child: Container(color: Colors.green),
),
],
)

5. Explain the concept of a BottomNavigationBar in Flutter and how the ConvexBottomBar


enhances this functionality. Include an example of its implementation.
BottomNavigationBar is used for switching between pages at the bottom of the screen.
ConvexBottomBar:
A third-party package that gives stylish and animated bottom bars with a convex shape.
Steps:
1. Add convex_bottom_bar in pubspec.yaml.
2. Use ConvexAppBar in your Scaffold’s bottomNavigationBar.
Example:
bottomNavigationBar: ConvexAppBar(
items: [
TabItem(icon: Icons.home, title: 'Home'),
TabItem(icon: Icons.settings, title: 'Settings'),
],
initialActiveIndex: 0,
onTap: (int i) => setState(() => index = i),
)
6. Compare and contrast different animation widgets in Flutter like Animated Container,
Animated Opacity, and Hero.

Feature AnimatedContainer AnimatedOpacity Hero

Animates changes in size, Animates visibility by Animates a widget


Purpose color, position, padding, fading the widget in or transition between two
etc. out screens
Feature AnimatedContainer AnimatedOpacity Hero

Type of Shared element


Layout or visual changes Opacity (transparency)
Animation transition across screens

When navigating to
When any of its properties When the opacity value
Trigger another screen with
change (e.g., width, height) changes
matching tag

Moderate – needs same


Very easy – just change
Ease of Use Easy – no controller needed tag on both source and
opacity value
destination widgets

Requires
Yes Yes Yes
State?

Animating image or
Animated boxes, cards, Show/hide widgets like
Use Cases avatar between list and
buttons, containers text, images, pop-ups
detail view

Animating a photo from


Example Button resizing, color Fade in/out messages or
a grid view to a full-page
Widgets transitions icons
view

Animation Implicit animation (no need Special navigation


Implicit animation
Type for controller) animation
Unit-5 Design & Animation in Flutter
2 Marks Questions
1. What is Skeleton Text in Flutter, and why is it used?
Skeleton Text is a grey placeholder used to show loading content. It gives users a visual cue
that content is being loaded in the background.
Why it's used:
• To improve user experience.
• To show a temporary layout while data (like images or text) is loading.
• It makes the app feel faster and smoother.
Example:
Used in news or shopping apps to show grey boxes before the actual content loads.

2. How can you determine the UI orientation in a Flutter application?


You can check orientation using the following code:
MediaQuery.of(context).orientation
This returns either:
• Orientation.portrait
• Orientation.landscape
Why it's useful:
To change the layout depending on the screen direction (vertical or horizontal), like showing
different UI in mobile and tablet modes.

3. What is the purpose of the Animation widget in Flutter?


The Animation widget in Flutter is used to create smooth movements and transitions in your
app.
Purpose:
• To make UI more dynamic and attractive.
• To animate properties like size, position, color, etc.
• Helps in improving user interaction and experience.
Example:
Button growing when tapped, fading images, or sliding menus.

4. What is Tween animation in Flutter?


Tween stands for “in-between”. Tween animation defines the start and end values of a
property and Flutter calculates the values in between during the animation.
Use:
• Used with AnimationController to animate custom values like size, color, position, etc.
Example:
Tween(begin: 0.0, end: 100.0)
This tween smoothly changes value from 0 to 100.

5. What is Ripple animation, and how is it typically used in Flutter applications?


Ripple animation is the wave-like visual effect that appears when a user taps on a button or
a widget.
In Flutter:
• It is automatically provided by widgets like InkWell and InkResponse.
Why it's used:
• To give feedback to the user that a tap or press happened.
• Makes the UI more interactive and responsive.
Example:
InkWell(
onTap: () {},
child: Text("Tap Me"),
)
4 Marks Questions
1. How to animate a container in Flutter? Provide a simple code example
In Flutter, you can animate a container using the AnimatedContainer widget. It allows you to
change its size, color, position, etc., with a smooth animation.
How it works:
• It is used inside a StatefulWidget.
• When a property like width or color changes, Flutter animates the change
automatically.
• You need to give it a duration.
Example Code:
bool isBig = false;
AnimatedContainer(
duration: Duration(seconds: 1),
width: isBig ? 200 : 100,
height: 100,
color: isBig ? Colors.blue : Colors.red,
)
Why it is useful:
• Easy to implement animations.
• Makes the UI smooth and interactive.
• No need for complex animation controllers.

2. Describe the concept of physics simulation in animation. How can it enhance user
experience in Flutter?
Physics simulation in animation means creating movement that follows real-world behavior
like gravity, bouncing, friction, etc.
Concept:
• Instead of moving objects at fixed speed, animations respond to forces (like a
bouncing ball).
• Flutter has classes like SpringSimulation, FrictionSimulation.
Examples in Flutter:
• BouncingScrollPhysics adds a bounce when the user scrolls to the end.
• DraggableScrollableSheet behaves like a sheet that you can drag with momentum.
How it helps user experience:
• Feels more natural and realistic.
• Makes apps more fun and interactive.
• Gives smooth, responsive feedback to user actions.

3. What is Radial Hero animation? How does it differ from standard Hero animations?
Provide an example.
Radial Hero animation is a type of circular transition where a widget expands or contracts in
a circle during screen navigation.
Standard Hero vs Radial Hero:

Feature Standard Hero Radial Hero

Shape Maintains same size or rectangular Expands/contracts in circular form

Animation Type Straight movement between screens Circular growth or shrink

Example Use Case:


• Clicking a small circular avatar that expands to a full profile page.
Implementation Concept:
You need to:
• Use Hero widget with same tag.
• Wrap the widget in ClipOval and animate its size to create radial effect.
Hero(
tag: 'profilePic',
child: ClipOval(
child: Image.asset('assets/avatar.png', width: 50),
),
)
Why it’s useful:
• Creates beautiful visual effects.
• Adds smooth transition to navigation.
• Great for user profile, galleries, or app launch animations.

4. How to implement Lottie animations in Flutter? What are the benefits of using Lottie?
Lottie is a library for rendering vector animations in JSON format. These animations are
made using Adobe After Effects and exported using the Bodymovin plugin.
Steps to Use Lottie in Flutter:
1. Add dependency in pubspec.yaml:
lottie: ^2.6.0
2. Import the package:
Import 'package:lottie/lottie.dart';
3. Use animation in your widget:
Lottie.asset('assets/animation.json')
Benefits of Lottie:
• Lightweight: Much smaller file size than GIFs.
• High quality: Animations are smooth and sharp at any resolution.
• Easy to use: Just one line of code to load a complex animation.
• Customizable: You can control speed, looping, etc.
Where it's used:
• Splash screens
• Onboarding animations
• Loading indicators
• Success/failure alerts

5. How to use the AnimatedContainer widget in Flutter? Include its properties and use
cases.
AnimatedContainer is a widget in Flutter that lets you animate changes in its properties like
size, color, padding, margin, etc.
Important Properties:

Property Description

duration Time for animation (required)

width Width of container

height Height of container

color Background color

curve Defines the style of animation

How it works:
• When any property changes, Flutter automatically animates it.
• Works only inside a StatefulWidget.
Use Cases:
• Animated buttons
• Resizable cards
• UI transitions
• Toggling between expanded/collapsed states
Example:
AnimatedContainer(
duration: Duration(milliseconds: 500),
width: 150,
height: 150,
color: Colors.green,
curve: Curves.easeInOut,
)
Why it’s useful:
• No need for an animation controller.
• Makes UI more interactive and modern.
• Very easy to implement for beginners.

6 Marks Questions
1.Explain the process of creating a custom animation using the AnimationController and
Tween classes in Flutter. Provide a detailed code example.
To create custom animations in Flutter, we use AnimationController and Tween. This allows
us to animate values over time, like size, position, or color.
Steps:
1. Use a StatefulWidget.
2. Create an AnimationController to control animation time and direction.
3. Use a Tween to define the start and end values.
4. Use Animation object to connect Tween and Controller.
5. Start the animation with controller.forward() or reverse().
Code Example:
class MyAnimation extends StatefulWidget {
@override
_MyAnimationState createState() => _MyAnimationState();
}
class _MyAnimationState extends State<MyAnimation> with SingleTickerProviderStateMixin
{
late AnimationController _controller;
late Animation<double> _animation;
@override
void initState() {
super.initState();
_controller = AnimationController(
duration: Duration(seconds: 2),
vsync: this,
);
_animation = Tween<double>(begin: 0, end: 200).animate(_controller)
..addListener(() {
setState(() {}); // Rebuild UI with new value
});
_controller.forward(); // Start the animation
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Container(
width: _animation.value,
height: 100,
color: Colors.blue,
);
}
}
Why it’s useful:
• You get full control over animation timing.
• You can animate custom properties, like angles or positions.
• Can be used for loading bars, moving objects, etc.

2. Discuss the different types of animations available in Flutter and how they can be used
to improve the user interface. Include examples of at least three types.
Flutter provides several types of animations to improve app appearance and interactivity.
1. Implicit Animations
• Automatically animate changes in widget properties.
• Example: AnimatedContainer, AnimatedOpacity, AnimatedAlign.
AnimatedOpacity(
opacity: isVisible ? 1.0 : 0.0,
duration: Duration(seconds: 1),
child: Text("Hello!"),
)
2. Explicit Animations
• Give full control using AnimationController and Tween.
• Example: Custom size animation or movement.
3. Physics-based Animations
• Add realistic motion using gravity, friction, etc.
• Example: DraggableScrollableSheet, BouncingScrollPhysics.
Benefits:
• Make UI more smooth and interactive.
• Provide better feedback to users.
• Improve visual flow and transitions.
3. Describe how to implement a complex animation sequence using multiple animation
widgets in Flutter. Provide a code example that demonstrates this.
You can build a complex animation sequence by combining multiple animations together
using AnimationController, Tween, and AnimatedBuilder.
Concept:
• Use AnimationController with different Tween objects.
• Add delay or timing using Interval.
• Combine in a single widget using AnimatedBuilder.
Example:
class ComplexAnimation extends StatefulWidget {
@override
_ComplexAnimationState createState() => _ComplexAnimationState();
}
class _ComplexAnimationState extends State<ComplexAnimation> with
SingleTickerProviderStateMixin {
late AnimationController _controller;
late Animation<double> sizeAnimation;
late Animation<Color?> colorAnimation;

@override
void initState() {
super.initState();
_controller = AnimationController(duration: Duration(seconds: 3), vsync: this);
sizeAnimation = Tween<double>(begin: 100, end: 200).animate(
CurvedAnimation(parent: _controller, curve: Interval(0.0, 0.5)),
);
colorAnimation = ColorTween(begin: Colors.red, end: Colors.blue).animate(
CurvedAnimation(parent: _controller, curve: Interval(0.5, 1.0)),
);
_controller.forward();
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: _controller,
builder: (context, child) {
return Container(
width: sizeAnimation.value,
height: sizeAnimation.value,
color: colorAnimation.value,
);
},
);
}
}
Why it’s useful:
• Used for animated buttons, page transitions, or loaders.
• Helps in chaining animations smoothly.
4. Illustrate the use of physics-based animations in Flutter, including how to use the
SpringSimulation and FrictionSimulation classes. Provide a practical example.
Flutter allows physics-based animations that mimic real-world movement, using
SpringSimulation and FrictionSimulation.
1. SpringSimulation
• Animates like a spring (bounce effect).
• Useful for widgets that expand or drop with elasticity.
2. FrictionSimulation
• Creates animations that slow down naturally like sliding.
• Used for drag effects or inertia-based movements.
Example:
SpringDescription spring = SpringDescription(
mass: 1,
stiffness: 100,
damping: 5,
);
Simulation simulation = SpringSimulation(spring, 0, 1, 2);
_controller.animateWith(simulation);
Use Cases:
• Interactive UI components (like bottom sheets, cards).
• Animations that feel smooth and responsive.
• Apps with scroll or gesture-based actions.

5. Explain the concept of Hero animations in Flutter, including how to implement Radial
Hero animations and their use cases in mobile applications.
Hero animation provides a smooth transition of a widget (like an image or button) between
two screens. Flutter matches widgets with the same tag on both screens and animates the
transition.
Basic Hero Animation Example:
Hero(
tag: 'imageTag',
child: Image.asset('assets/image.jpg', width: 100),
)
• On the second screen, use the same Hero tag with the full-size image.
Radial Hero Animation
• It is a circular version of Hero animation.
• The widget expands from a circle into full screen or shrinks back to a circle.
Difference:

Hero Animation Radial Hero Animation

Moves widget normally Moves + scales in circular shape

Simple implementation Requires custom animation

Use Cases:
• Profile picture zoom
• Gallery view open
• Splash screen to homepage transition
Unit-6 Forms, navigation & Routing in Flutter
2 Marks Questions
1. What is form validation in Flutter?
Form validation in Flutter means checking whether the user has entered valid data in form
fields. For example, making sure an email field contains a valid email, or a password field is
not empty. Flutter provides built-in support using the Form and TextFormField widgets with
validation logic.

2. How do you define a TextFormField in Flutter?


TextFormField is used to take user input and supports validation.
Example:
TextFormField(
decoration: InputDecoration(labelText: 'Name'),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter your name';
}
return null;
},
)

3. What is the purpose of Navigator.push() in Flutter?


Navigator.push() is used to move from one screen (or page) to another in a Flutter app. It
places a new route on top of the stack, so the user can return to the previous screen with
Navigator.pop().
Example:
Navigator.push(context, MaterialPageRoute(builder: (context) => SecondPage()));
4. Define named routes in Flutter.
Named routes help you manage screen navigation by assigning each route a name (string).
This makes the code cleaner and easier to manage when the app has many screens.
Example:
Navigator.pushNamed(context, '/home');
In MaterialApp:
dart
CopyEdit
routes: {
'/home': (context) => HomePage(),
}

5. What is a WebSocket?
A WebSocket is a communication protocol that allows real-time two-way interaction
between the client (like a Flutter app) and server. It is used for chat apps, live notifications,
etc.

6. How do you send data as arguments using named routes?


You can pass data using the arguments property of Navigator.pushNamed.
Example:
Navigator.pushNamed(context, '/details', arguments: 'Hello Data');
In the receiving screen:
final data = ModalRoute.of(context)!.settings.arguments;

7. Write a simple URL launch command in Flutter.


To open a website link, use the url_launcher package.
Example:
launchUrl(Uri.parse("https://flutter.dev"));
Add dependency:
url_launcher: ^6.1.5

8. What is the role of the Form widget in Flutter?


The Form widget groups multiple input fields like TextFormField and handles validation and
submission together. It helps to manage the form’s state and validate data all at once.

9. Mention one way to read data from Firebase in Flutter.


Using Firebase’s cloud_firestore package:
dart
CopyEdit
FirebaseFirestore.instance.collection('users').get().then((snapshot) {
for (var doc in snapshot.docs) {
print(doc.data());
}
});
This reads data from the 'users' collection.

10. How can you send an email in a Flutter application?


Use the url_launcher package to open the default email app:
launchUrl(Uri.parse("mailto:test@example.com?subject=Hello&body=How are you?"));

4 Marks Questions
1. Explain how form validation is performed using Form and TextFormField in Flutter.
In Flutter, form validation is done using the Form widget and TextFormField inputs. You
define a GlobalKey to control the form state. Inside each TextFormField, the validator
function checks if the input is valid.
Steps:
1. Wrap input fields in a Form widget.
2. Use TextFormField for inputs.
3. Define validator for each field.
4. On submit, check using formKey.currentState!.validate().
Example:
final _formKey = GlobalKey<FormState>();
Form(
key: _formKey,
child: Column(
children: [
TextFormField(
validator: (value) => value!.isEmpty ? 'Enter name' : null,
),
ElevatedButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
print("Form is valid");
}
},
child: Text("Submit"),
),
],
),
);

2. Describe the steps to navigate between two pages using named routes in Flutter.
Named routes make navigation simple by assigning a name (string) to each screen.
Steps:
1. Define routes in MaterialApp:
MaterialApp(
initialRoute: '/',
routes: {
'/': (context) => HomePage(),
'/second': (context) => SecondPage(),
},
);
2. Navigate to another page:
Navigator.pushNamed(context, '/second');
3. To go back:
Navigator.pop(context);
Benefits:
• Easy to manage many screens.
• Clean navigation code.

3. What is a WebSocket and how is it implemented in Flutter?


A WebSocket allows real-time two-way communication between client and server.
Use in Flutter:
Use the web_socket_channel package.
Steps:
1. Add dependency:
web_socket_channel: ^2.4.0
2. Connect and send/receive:
final channel = WebSocketChannel.connect(
Uri.parse('ws://echo.websocket.org'),
);

channel.sink.add('Hello');
channel.stream.listen((data) {
print(data);
});
Use Cases:
• Chat apps
• Live updates (stocks, notifications)

4. Describe how you can pass arguments to a route using named routes.
Flutter allows sending data (arguments) when navigating using named routes.
Steps:
1. Pass arguments like this:
Navigator.pushNamed(context, '/details', arguments: 'Hello');
2. Access arguments in the second screen:
final args = ModalRoute.of(context)!.settings.arguments as String;
This helps in passing user data, IDs, etc., between screens.

5. Explain how to write data to Firebase Firestore or Realtime Database using Flutter.
To write data to Firebase, use either Firestore or Realtime Database.
Firestore (NoSQL):
1. Add cloud_firestore package.
2. Write data:
FirebaseFirestore.instance.collection('users').add({
'name': 'John',
'email': 'john@example.com',
});
Realtime Database:
1. Add firebase_database package.
2. Write data:
DatabaseReference ref = FirebaseDatabase.instance.ref("users/user1");
ref.set({
'name': 'John',
'email': 'john@example.com',
});

6. Design a simple form submission page with name, email, and submit button.
class MyFormPage extends StatefulWidget {
@override
_MyFormPageState createState() => _MyFormPageState();
}
class _MyFormPageState extends State<MyFormPage> {
final _formKey = GlobalKey<FormState>();
String name = '', email = '';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Form")),
body: Form(
key: _formKey,
child: Column(
children: [
TextFormField(
decoration: InputDecoration(labelText: 'Name'),
onChanged: (val) => name = val,
validator: (val) => val!.isEmpty ? 'Enter name' : null,
),
TextFormField(
decoration: InputDecoration(labelText: 'Email'),
onChanged: (val) => email = val,
validator: (val) => val!.isEmpty ? 'Enter email' : null,
),
ElevatedButton(
child: Text("Submit"),
onPressed: () {
if (_formKey.currentState!.validate()) {
print('Submitted: $name, $email');
}
},
)
],
),
),
);
}
}

7. How do you send SMS using Flutter plugins? Mention any two useful plugins.
Flutter does not send SMS directly but can open the SMS app using plugins.
1. url_launcher:
launchUrl(Uri.parse('sms:1234567890?body=Hello'));
2. telephony (for background SMS):
Allows sending SMS directly (requires permission).
Telephony telephony = Telephony.instance;
telephony.sendSms(to: "1234567890", message: "Hi!");

8. Explain how the Navigator.pop() method is used in a multi page application.


Navigator.pop(context) is used to go back to the previous screen.
Example:
If a user navigated from Screen A to Screen B using Navigator.push(), then pressing a back
button or calling Navigator.pop() will take them back to A.
ElevatedButton(
onPressed: () {
Navigator.pop(context);
},
child: Text("Go Back"),
);

9. Describe the process of navigating between two screens using Navigator.push() and
Navigator.pop().
Flutter uses a stack system to manage navigation.
To go to another screen:
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SecondPage()),
);
To go back to the previous screen:
Navigator.pop(context);
Use case:

• Screen A ➝ push ➝ Screen B

• Screen B ➝ pop ➝ Screen A

10. Describe how to structure a multi page application in Flutter with examples.
In a multi-page Flutter app:
• Each screen is a separate widget.
• Navigation is done using Navigator and routes.
Steps:
1. Create screens like HomePage, AboutPage, etc.
2. Define them in routes:
MaterialApp(
initialRoute: '/',
routes: {
'/': (context) => HomePage(),
'/about': (context) => AboutPage(),
},
)
3. Navigate using:
Navigator.pushNamed(context, '/about');
Benefits:
• Clean code structure.
• Easy to manage navigation.
6 Marks Questions
1. Create a complete example of a form submission page in Flutter with validation and
navigation to a confirmation page.
This app has two screens:
• A Form Screen with validation.
• A Confirmation Screen that opens after successful submission.
Code:
// main.dart
void main() {
runApp(MaterialApp(
initialRoute: '/',
routes: {
'/': (context) => FormPage(),
'/confirm': (context) => ConfirmationPage(),
},
));
}
class FormPage extends StatelessWidget {
final _formKey = GlobalKey<FormState>();
final nameController = TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Form')),
body: Form(
key: _formKey,
child: Column(
children: [
TextFormField(
controller: nameController,
validator: (value) => value!.isEmpty ? 'Enter your name' : null,
decoration: InputDecoration(labelText: 'Name'),
),
ElevatedButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
Navigator.pushNamed(context, '/confirm',
arguments: nameController.text);
}
},
child: Text('Submit'),
)
],
),
),
);
}
}
class ConfirmationPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
final name = ModalRoute.of(context)!.settings.arguments as String;
return Scaffold(
appBar: AppBar(title: Text('Confirmation')),
body: Center(child: Text('Thank you, $name!')),
);
}
}

2. Explain the concept of named routes with arguments in detail. Create a sample app
structure using it.
Named Routes help navigate between screens using a string name instead of creating
MaterialPageRoute objects.
Passing arguments lets us send data between screens.
Steps:
1. Define routes in MaterialApp.
2. Use Navigator.pushNamed to navigate.
3. Use ModalRoute.of(context) to receive arguments.
Example:
// main.dart
routes: {
'/': (context) => FirstScreen(),
'/second': (context) => SecondScreen(),
}
// Sending data
Navigator.pushNamed(context, '/second', arguments: 'Hello');
// Receiving data
final message = ModalRoute.of(context)!.settings.arguments as String;
Benefits:
• Cleaner navigation code.
• Better for large apps with many screens.
• Easier state/data passing.

3. Design a multi-page Flutter app with three screens (Home, Profile, Settings) using
named routes. Describe navigation flow.
App Structure:
• HomePage: /
• ProfilePage: /profile
• SettingsPage: /settings
Navigation Flow:
• From Home → Profile or Settings using Navigator.pushNamed
• Can go back using Navigator.pop
Example Code:
// main.dart
routes: {
'/': (context) => HomePage(),
'/profile': (context) => ProfilePage(),
'/settings': (context) => SettingsPage(),
}
// HomePage
ElevatedButton(
onPressed: () => Navigator.pushNamed(context, '/profile'),
child: Text("Go to Profile"),
);

4. Demonstrate how to establish a WebSocket connection in Flutter and exchange data


with a server.
Use the web_socket_channel package.
Steps:
1. Add package to pubspec.yaml:
web_socket_channel: ^2.4.0
2. Example code:
import 'package:web_socket_channel/web_socket_channel.dart';
final channel = WebSocketChannel.connect(
Uri.parse('wss://echo.websocket.events'),
);
// Send a message
channel.sink.add('Hello Server');
// Receive message
channel.stream.listen((message) {
print('Received: $message');
});
Use Cases:
• Real-time chat
• Live game updates
• Notifications

5. Describe the steps to read and write structured data from Firebase in a Flutter app.
Include Firebase setup and code samples.
Setup:
1. Add Firebase to Flutter project.
2. Add firebase_core, cloud_firestore packages.
3. Initialize Firebase in main():
await Firebase.initializeApp();
Write Data:
FirebaseFirestore.instance.collection('users').add({
'name': 'Vishva',
'email': 'vishva@email.com',
});
Read Data:
FirebaseFirestore.instance.collection('users').get().then((snapshot) {
for (var doc in snapshot.docs) {
print(doc.data());
}
});
Use Cases:
• Store user profiles
• Fetch product lists
• Real-time updates

6. Develop a use-case scenario where the user fills a form, data is sent to Firebase, and a
confirmation SMS is sent using Flutter.
Use Case:
A user enters name and phone number, data is stored in Firebase, and SMS is sent.
Steps:
1. Use TextFormField for inputs.
2. Validate and submit to Firebase:
FirebaseFirestore.instance.collection('contacts').add({
'name': name,
'phone': phone,
});
3. Use url_launcher to send SMS:
launchUrl(Uri.parse('sms:$phone?body=Thank you for registering!'));
Plugins:
• cloud_firestore
• url_launcher
This creates a complete form + Firebase + SMS flow.

7. Write and explain a Flutter program that includes a form with two Text Form Fields (e.g.,
username and password) and validates them.
Code Example:
final _formKey = GlobalKey<FormState>();
Form(
key: _formKey,
child: Column(
children: [
TextFormField(
decoration: InputDecoration(labelText: 'Username'),
validator: (val) => val!.isEmpty ? 'Enter username' : null,
),
TextFormField(
decoration: InputDecoration(labelText: 'Password'),
obscureText: true,
validator: (val) => val!.length < 6 ? 'Password too short' : null,
),
ElevatedButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
print('Form is valid!');
}
},
child: Text('Login'),
)
],
),
);

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy