MAD solution
MAD solution
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.
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
void display() {
print("Name: $name");
}
}
Classes help organize code and enable object-oriented programming.
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.
✦ 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.
✦ 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.
✦ 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.
✦ 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.
✦ 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.
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.
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. 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.
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.
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
}
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.
Change in UI Can’t change after build Can change when state changes
Example use Static UI like labels, icons Counters, form inputs, etc.
Example:
• Use Stateless for displaying a title.
• Use Stateful for a like button that changes color when clicked.
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"),
);
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.
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"),
],
),
),
);
}
}
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.
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.
UI update Can’t change once built Can change based on user interaction
Example use Text, logo, static screen Forms, toggle switch, counter app
2. Compare Flutter with other mobile development frameworks like React Native or
Xamarin.
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.
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")
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.
Example:
Icon(Icons.home, size: 30, color: Colors.blue)
Space inside a widget (around its Space outside a widget (around its
Meaning
content) border)
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"),
)
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.
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")
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
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:
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 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.
Widget Behavior
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),
)
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")]),
),
)
Use Cases:
• FAQ sections
• List of expandable settings
Example:
ExpansionTile(
title: Text("More Info"),
children: [Text("Here is the detailed information.")],
)
Type Description
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),
),
],
)
Use Case:
• Clock apps
• Dashboards
• Learning projects
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
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),
),
],
)
When navigating to
When any of its properties When the opacity value
Trigger another screen with
change (e.g., width, height) changes
matching tag
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
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:
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
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:
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.
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.
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.
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!");
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:
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"),
);
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'),
)
],
),
);