[go: up one dir, main page]

0% found this document useful (0 votes)
12 views201 pages

Flutter Lab Manual

Uploaded by

mdateeq807
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)
12 views201 pages

Flutter Lab Manual

Uploaded by

mdateeq807
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/ 201

lOMoARcPSD|58593188

Flutter LAB Manual with CO-PO mapping (1)

CSE - data mining (Marri Laxman Reddy Institute of Technology and Management)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Md Ateeq (mdateeq807@gmail.com)
lOMoARcPSD|58593188

Department of Computer Science and Engineering

UI-FLUTTER LAB
III B.TECH -I SEMESTER (CSE)
R22 (MLRS )REGULATION

A.Y: 2024-25

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

CERTIFICATE

This is to certify that this manual is a bonafide record of practical work in the WEB
TECHNOLOGIES in III B. Tech, II semester (CSE) programme during the academic year
2023-24. This book is prepared by Dr. S. Pratap singh, Mr. G Moses, Mrs. Pallavi, Mr.
Satchidanandam department of Computer Science and Engineering.

LAB I/C Head of the Department

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

PREFACE

This Lab Manual entitled “Web Technologies Lab” is intended for the use of III B. Tech II Semester
Computer Science and Engineering students of Marri Laxman Reddy Institute of Technology and
Management, Dundigal, Hyderabad. The main objective of the Flutter is Google's UI toolkit for
building applications for mobile, web, and desktop from a single codebase. In this codelab, you will
build the following Flutter application: The application generates cool-sounding names, such as
"newstay", "lightstream", "mainbrake", or "graypine".

By

Dr. S. Pratap Singh

Mr. Sachidanandham

Mrs. M.Pallavi

Mr. G Moses

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

VISION & MISSION OF INSTITUTION

Vision:

To be as an ideal academic institution by graduating talented engineers to be

ethically strong, competent with quality research and technologies.

Mission:

 Utilize rigorous educational experiences to produce talented engineers

 Create an atmosphere that facilitates the success of students

 Programs that integrate global awareness, communication skills and Leadership qualities

 Education and Research partnership with institutions and industries to prepare

the students for interdisciplinary research

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

VISION & MISSION OF DEPARTMENT

Vision:

To empower the students to be technologically adept, innovative, self-motivated


and responsible global citizen possessing human values and contribute
significantly towards high quality technical education with ever changing world.

Mission:

 To offer high-quality education in the computing fields by providing an


environment where the knowledge is gained and applied to participate in
research, for both students and faculty.
 To develop the problem solving skills in the students to be ready to deal with
cutting edge technologies of the industry.
 To make the students and faculty excel in their professional fields by
inculcating the communication skills, leadership skills, team building skills
with the organization of various co-curricular and extra-curricular
programmes.
 To provide the students with theoretical and applied knowledge, and adopt an
education approach that promotes lifelong learning and ethical growth.

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

Program Educational Objectives

PEO1 : To induce strong foundation in mathematical and core concepts, which


enable them to participate in research, in the field of computer science.
PEO2 : To be able to become the part of application development and problem
solving by learning the computer programming methods, of the industry and related
domains.
PEO3 : To gain the multidisciplinary knowledge by understanding the scope of
association of computer science engineering discipline with other engineering
disciplines.
PEO4 : To improve the communication skills, soft skills, organizing skills which
build the professional qualities, there by understanding the social responsibilities and
ethical attitude.

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

PROGRAM OUTCOMES(POs)
Engineering Graduates will be able to:
1. Engineering Knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals, and an engineering specialization to the solution of complex engineering
problems.

2. Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of mathematics,
natural sciences, and engineering sciences.

3. Design/development of solutions: Design solutions for complex engineering problems and


design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.
4. Conduct investigations of complex problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of
the information to provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities
with an understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to
the professional engineering practice.
7. Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and need
for sustainable development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or leader in
diverse teams, and in multidisciplinary settings.

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

10. Communication: Communicate effectively on complex engineering activities with the


engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and receive
clear instructions.

11. Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.

12. Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.

PROGRAM SPECIFIC OUTCOMES


(PSOs)

PSO1: Applications of Computing: Ability to use knowledge in various domains to provide


solution to new ideas and innovations.

PSO2: Programming Skills: Identify required data structures, design suitable algorithms, develop
and maintain software for real world problems

PSO 3: Make use of computational and experimental tools for creating innovative career paths,
to be an entrepreneur and desire for higher studies.

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

R22 B.TECH CSE SYLLABUS


CS506PC: UI DESIGN - FLUTTER

B.Tech. III Year I Sem. L TPC


0 0 2 1
Course Objectives:
 Learns to Implement Flutter Widgets and Layouts
 Understands Responsive UI Design and with Navigation in Flutter
 Knowledge on Widges and customize widgets for specific UI elements, Themes
 Understand to include animation apart from fetching data

Course Outcomes:
 Implements Flutter Widgets and Layouts
 Responsive UI Design and with Navigation in Flutter
 Create custom widgets for specific UI elements and also Apply styling using themes and
custom styles.
 Design a form with various input fields, along with validation and error handling
 Fetches data and write code for unit Test for UI components and also animation

List of Experiments: Students need to implement the following experiments


1. a) Install Flutter and Dart SDK.
b) Write a simple Dart program to understand the language basics.

2. a) Explore various Flutter widgets (Text, Image, Container, etc.).


b) Implement different layout structures using Row, Column, and Stack widgets.

3. a) Design a responsive UI that adapts to different screen sizes.


b) Implement media queries and breakpoints for responsiveness.

4. a) Set up navigation between different screens using Navigator.


b) Implement navigation with named routes.

5. a) Learn about stateful and stateless widgets.


b) Implement state management using set State and Provider.

6. a) Create custom widgets for specific UI elements.


b) Apply styling using themes and custom styles.

7. a) Design a form with various input fields.


b) Implement form validation and error handling.

8. a) Add animations to UI elements using Flutter's animation framework.


b) Experiment with different types of animations (fade, slide, etc.).

9. a) Fetch data from a REST API.


b) Display the fetched data in a meaningful way in the UI.
Downloaded by Md Ateeq (mdateeq807@gmail.com)
lOMoARcPSD|58593188

10. a) Write unit tests for UI components.


b) Use Flutter's debugging tools to identify and fix issues.

TEXT BOOK:
11. 1. Marco L. Napoli, Beginning Flutter: A Hands-on Guide to App Development.

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

CO-PO-PSO Mapping Matrix:

CO\PO/PSO PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2 PSO3
CO1:
Implements
Flutter 3 2 3 - 3 - - 3 - 3
Widgets and
Layouts
CO2:
Responsive
UI Design
3 2 3 - 3 2 - 3 - 3
and
Navigation
in Flutter
CO3: Create
custom
3 2 3 - 3 1 - 3 - 3
widgets and
apply styling
CO4: Design
a form with
validation 2 3 3 2 3 - 2 3 2 3
and error
handling
CO5:
Fetches data,
writes code
3 3 3 3 3 - - 3 3 3
for unit
testing and
animation

Justification for Mapping:


CO1: Implements Flutter Widgets and Layouts

 PO1 (Engineering knowledge): Demonstrates understanding of Flutter layouts and widgets (3).
 PO2 (Problem analysis): Requires analysis of UI layout problems (2).
 PO3 (Design/development of solutions): Focuses on designing user interfaces using Flutter widgets (3).
 PO5 (Modern tool usage): Uses modern mobile development tools like Flutter (3).
 PSO1: Aligns with understanding and designing web/mobile UI elements (3).
 PSO3: Promotes modern tools for innovative solutions (3).

CO2: Responsive UI Design and Navigation in Flutter

 PO1: Demonstrates knowledge of responsive UI and navigation (3).


 PO2: Analyzing different device sizes and user interaction (2).
 PO3: Emphasizes design of responsive and navigational components (3).
 PO5: Uses modern tools for building responsive UIs (3).
 PO6 (Engineer and society): Focus on real-world usability and societal needs (2).
 PSO1: Related to web/mobile design and user experience design (3).
 PSO3: Focuses on modern tools and innovative paths (3).

CO3: Create Custom Widgets and Apply Styling

 PO1: Understanding principles of creating custom widgets and styling (3).


 PO2: Problem-solving for custom widget creation and reuse (2).
 PO3: Emphasizes on designing specific UI solutions (3).
 PO5: Leveraging Flutter’s advanced features for styling (3).
Downloaded by Md Ateeq (mdateeq807@gmail.com)
lOMoARcPSD|58593188

 PO6: Applying custom styles based on societal or user preferences (1).


 PSO1: Involves custom solution designs in web/mobile contexts (3).
 PSO3: Encourages innovative approaches using modern tools (3).

CO4: Design a Form with Validation and Error Handling

 PO1: Understanding form elements and validation techniques (2).


 PO2: Focuses on handling errors and data validation problems (3).
 PO3: Development of solutions for form-based applications (3).
 PO4 (Investigation of complex problems): Investigating and solving validation issues (2).
 PO5: Uses Flutter for form design and validation tools (3).
 PO9 (Individual and teamwork): Collaborating for form creation and testing (2).
 PSO1: Related to programming and interface handling (3).
 PSO2: Ensuring reliability of forms and data integrity (2).
 PSO3: Uses modern tools to ensure form reliability and error handling (3).

CO5: Fetches Data, Writes Code for Unit Testing and Animation

 PO1: Understanding of data-fetching mechanisms and animations (3).


 PO2: Analyzing complex data-fetching issues and animation performance (3).
 PO3: Focuses on developing unit tests for ensuring UI correctness (3).
 PO4: Investigating the correctness of UI components and animations (3).
 PO5: Utilizes modern testing tools to ensure component accuracy (3).
 PSO1: Related to data management, programming, and testing for reliability (3).
 PSO2: Ensures software reliability, particularly with UI testing and error handling (3).
 PSO3: Modern tools are used for innovative career paths or entrepreneurship (3).

Mapping Levels:

 3: Highly related
 2: Moderately related
 1: Slightly related
 -: Not related

This matrix demonstrates how each CO aligns with specific POs and PSOs, ensuring comprehensive coverage of learning
objectives and skill development.

Experiment 1:
Downloaded by Md Ateeq (mdateeq807@gmail.com)
lOMoARcPSD|58593188

a) Install Flutter and Dart SDK.

System Requirements

● Operating System: Windows 10 or later (64-bit)


● Disk Space: 1.64 GB (does not include disk space for IDE/tools)
● Tools: Git for Windows 2.x, PowerShell 5.0, and a compatible IDE
(VS Code, Android Studio, IntelliJ)

Step 1: Get the Flutter SDK

1. Download the Flutter SDK:


○ Visit the Flutter SDK releases page.
○ Download the latest stable release of the Flutter SDK (the .zip file).
2. Extract the Flutter SDK:
○ Extract the downloaded .zip file and place the contained flutter
directory in a desired installation location (e.g., C:\src\flutter).

Step 2: Update Your Path

1. Locate Your System Path:


○ Open the Start Search, type in env, and select Edit the
system environment variables.
○ In the System Properties window, click on the Environment Variables
button.
2. Update Path:
○ In the User variables section, find the Path variable and click Edit.
○ Click New and add the full path to the flutter\bin directory
(e.g., C:\src\flutter\bin).
○ Click OK to close all windows.
3. Verify Flutter is Added:

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

○ Open a new Command Prompt or PowerShell window and run flutter


doctor.

Step 3: Run flutter doctor

1. Open Command Prompt or PowerShell:


○ Type cmd or powershell in the Start menu and open it.
2. Run flutter doctor:
○ In the terminal, type flutter doctor and press Enter.
○ This command checks your environment and displays a report of
the status of your Flutter installation.

Step 4: Install Android Studio

1. Download Android Studio:


○ Visit the Android Studio download page and download the installer.
2. Install Android Studio:
○ Run the installer and follow the setup wizard to complete the installation.
○ During installation, make sure the boxes for the following are checked:
■ Android SDK
■ Android SDK Platform
■ Android Virtual Device
3. Setup Android Studio:
○ Open Android Studio.
○ Complete the Android Studio Setup Wizard, which includes
downloading the Android SDK components.

Step 5: Set Up the Android Emulator

1. Open Android Studio:


○ Go to Tools > AVD Manager.
2. Create a Virtual Device:
○ Click on Create Virtual Device, select a hardware profile, and click Next.

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

○ Select a system image (e.g., x86 Images tab), download if


necessary, and click Next.
○ Click Finish to create the AVD.

Step 6: Set Up the IDE (Visual Studio Code)

1. Download VS Code:
○ Visit the Visual Studio Code download page and download the installer.
2. Install VS Code:
○ Run the installer and follow the setup wizard to complete the installation.
3. Install Flutter and Dart Plugins:
○ Open VS Code.
○ Go to Extensions (Ctrl+Shift+X).
○ Search for and install the Flutter and Dart extensions.

Step 7: Set Up the Flutter Device

1. Enable Developer Mode on Your Device:


○ Go to Settings > About phone and tap the Build number 7
times to unlock developer options.
○ Go to Settings > System > Developer options and enable USB
debugging.
2. Connect Your Device:
○ Connect your Android device to your computer via USB.
○ Run flutter devices in the terminal to verify that Flutter recognizes
your connected device.

Step 8: Create and Run a New Flutter Project

1. Create a New Flutter Project:


○ In VS Code, open the command palette (Ctrl+Shift+P).
○ Type Flutter: New Project, then press Enter.
○ Select a project name and location to save the project.
2. Run the Flutter Project:
○ Open the main.dart file in your new project.
○ Press F5 to start debugging and run your app.

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

That's it! You now have Flutter installed and set up on your Windows machine. You can
start building Flutter applications. If you encounter any issues, the flutter doctor
command can provide helpful diagnostics.

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

1 . b) Write a simple Dart program to understand the


language basics.

import 'package:flutter/material.dart';

void main() {

runApp(Abc());

class Abc extends StatelessWidget

{ @override

Widget build(BuildContext context)

{ return MaterialApp(

home: Def(),

);

class Def extends StatelessWidget

{ const Def({super.key});

@override

Widget build(BuildContext context)

{ return Scaffold(

appBar: AppBar(

title: Text("Welcome"),

backgroundColor: Colors.purple,

),

body: Column(

children: [

//Widgets

],

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

),);}}

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

1. What is Dart?

Dart is an object-oriented programming language developed by


Google, designed for building mobile, desktop, server, and web
applications.

2. What is a Future in Dart?

A Future represents a potential value or error that will be available at


some point in the future, commonly used in asynchronous
programming.

3. What does the async keyword do in Dart?

The async keyword is used to define a function as asynchronous,


allowing the use of await within the function to pause execution until a
Future completes.

4. How do you declare a list in Dart?

A list in Dart can be declared using List, for example: List<int>


numbers = [1, 2, 3];.

5. What is null safety in Dart?

Null safety in Dart ensures variables cannot contain null values unless
explicitly declared as nullable using a question mark (e.g., String?).

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

6. What are the key features of the Dart programming language?

Dart is an object-oriented, class-defined language that uses a C-style


syntax. It supports strong typing, asynchronous programming with
async and await, and a rich standard library. It's designed for front-
end development but can also be used for back-end and command- line
applications.

7. Explain the difference between var, final, and const in Dart.

var is used for variables whose type will be inferred at runtime. final is
used for variables that can only be set once but are initialized at
runtime. const is used for compile-time constants and variables
initialized at compile-time.

8. How does Dart handle asynchronous programming?

Dart handles asynchronous programming using Future, async, and await.


Future represents a potential value or error that will be available at
some point. async is used to declare a function as asynchronous, and
await pauses the function execution until the awaited Future
completes.

9. What are the different types of collections in Dart?

Dart provides several types of collections including List, Set, and


Map. List is an ordered collection of objects, Set is an unordered
collection of unique items, and Map is a collection of key-value pairs.

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

10. Explain the concept of null safety in Dart.

Null safety in Dart ensures that no variable can contain a null value unless
it is explicitly declared as nullable using a question mark (e.g., int?). This
helps to prevent null reference errors and improves code safety and
reliability.

11. What are the data types available in Dart?

Dart supports various data types including int, double, String, bool,
List, Map, Set, and more.

12. How do you define a class in Dart?

A class in Dart is defined using the class keyword, for example: class MyClass
{ /* class members */ }.

13. What is the difference between final and const in Dart?

final variables are initialized at runtime and can only be set once.
const variables are compile-time constants and are initialized
at compile-time.

14. What is a constructor in Dart?

A constructor is a special method of a class that is called when an


instance of the class is created. It is used to initialize the object's
properties.

15. How do you handle exceptions in Dart?

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

Exceptions in Dart are handled using try, catch, and finally blocks.
The try block contains code that may throw an exception, catch
handles the exception, and finally contains code that runs regardless of
whether an exception occurred.

16. What is Flutter and what are its main components?

Flutter is an open-source UI software development toolkit created by


Google. It is used to develop cross-platform applications from a single
codebase. The main components of Flutter are the Flutter framework,
the Flutter engine, and the Dart platform.

17. What is a widget in Flutter?

In Flutter, everything is a widget. Widgets are the building blocks of a


Flutter app's user interface. They describe what their view should look
like given their current configuration and state. Widgets can be
stateless or stateful, depending on whether they manage state.

18. Explain the difference between


StatelessWidget and StatefulWidget.

StatelessWidget is immutable and cannot change once it is built. It


does not have any internal state that changes over time.
StatefulWidget, on the other hand, is mutable and can change during
its lifecycle. It has a State object that holds the widget's mutable state.

19. How does the Flutter rendering process work?

The Flutter rendering process involves three main stages: layout,


painting, and compositing. During the layout stage, Flutter determines
the size and position of each widget. In the painting stage, Flutter
draws the visual representation of each widget. In the compositing

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

stage, Flutter combines the painted layers to create the final output on
the screen.

20. What is the build method in Flutter?

The build method in Flutter is used to describe how to display the


widget in terms of other lower-level widgets. It is called whenever the
widget's configuration changes.

21. How do you navigate between screens in Flutter?

Navigation between screens in Flutter is managed using the


Navigator widget, with methods like push, pop, pushReplacement,
and popUntil.

22. What is a Container widget in Flutter?

A Container widget in Flutter is a versatile widget that can contain


other widgets and apply padding, margins, borders, and background
color.

23. What is setState in Flutter?

setState is a method used in a StatefulWidget to update the state of


the widget and trigger a rebuild of the UI.

24. What is a Stream in Flutter?

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

A Stream is a sequence of asynchronous events. It is used to handle


asynchronous data, such as data received from a network request or
user input over time.

25. How do you add external packages to a Flutter project?


External packages are added to a Flutter project by specifying
them in the dependencies section of the pubspec.yaml file and
running flutter pub get.
26. What is hot reload in Flutter?

Hot reload is a feature in Flutter that allows you to quickly see


changes in your code by preserving the app's state and injecting
updated code into the running app.

27. How do you handle user input in Flutter?

User input in Flutter is handled using widgets like TextField for text
input, and GestureDetector for handling gestures like taps and swipes.

28. What is the MaterialApp widget?

MaterialApp is a widget that wraps several widgets that are


commonly required for Material Design applications. It provides an
easy way to set up the basic structure of a Flutter app.

29. What is a Scaffold widget?

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

The Scaffold widget provides a framework for implementing the


basic visual layout structure of the Material Design layout, including
the app bar, drawer, and bottom navigation bar.

30. What is the purpose of the pubspec.yaml file in a Flutter


project?

The pubspec.yaml file is used to define the project's dependencies,


assets, and metadata. It specifies the packages and plugins that the
project depends on, as well as other configurations such as the
project's version and description. This file is essential for managing
and organizing the project's resources and dependencies.

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

Experiment 2:
a) Explore various Flutter widgets (Text, Image, Container, etc.).
Text Widget:
import 'package:flutter/material.dart';

void main() {

runApp(MyApp());

class MyApp extends StatelessWidget

{ @override

Widget build(BuildContext context)

{ return MaterialApp(

home: Abc();

);}}

class Abc extends StatelessWidget

{ const Abc({super.key});

@override

Widget build(BuildContext context)

{ return Scaffold(

appBar: AppBar(title: Text('Text Widget Example')),

body: Center(

child: Text(

'Hello,

Flutter!',

style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),

),

),

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

Image Widgets
● Network Image

import 'package:flutter/material.dart';

void main() {

runApp(MyApp());

class MyApp extends StatelessWidget

{ @override

Widget build(BuildContext context)

{ return MaterialApp(

home: Abc(),

);

class Abc extends StatelessWidget

{ const Abc({super.key});

@override

Widget build(BuildContext context)

{ return Scaffold(

appBar: AppBar(

title: Text("Image Widget"),

),

body: Image.network('https://picsum.photos/250?image=9'),

);}}

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

Note: Must Add the Internet Tag in AndoridManifiest.yaml which is


inside Android Folder for giving the Internet access to the App.

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

● Asset Image or Local image

Add Images to Your Project

1. Create an assets directory: In your Flutter project root, create a directory named
assets (or any other name you prefer). And copy the image of your requirement
inside the assets folder.

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

2. Declare the assets: Open your pubspec.yaml file and add the assets under the
flutter section.

assets:

- assets/abc.jpeg

3. Open Terminal: give the command ‘flutter pub get’.


4. To Display Images in Your Flutter App, we will be using ‘Image.asset’ widget.
import

'package:flutter/material.dart'; void

main() {

runApp(MyApp());

class MyApp extends StatelessWidget

{ @override

Widget build(BuildContext context)

{ return MaterialApp(

home: Abc(),

);}}

class Abc extends StatelessWidget

{ const Abc({super.key});

@override

Widget build(BuildContext context)

{ return Scaffold(

appBar: AppBar(

title: Text("Image Widget"),

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

);}}

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

Container Widget
import 'package:flutter/material.dart';

void main() {

runApp(MyApp());

class MyApp extends StatelessWidget {

@override

Widget build(BuildContext context) {

return MaterialApp(

home: Abc(),

);

class Abc extends StatelessWidget {

const Abc({super.key});

@override

Widget build(BuildContext context) {

return Scaffold(

appBar: AppBar(title: Text('Container Widget Example')),

body: Center(

child: Container(

width: 200,

height: 200,

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

padding: EdgeInsets.all(16),

margin: EdgeInsets.all(16),

decoration: BoxDecoration(

color: Colors.blue,

borderRadius: BorderRadius.circular(8),

boxShadow: [

BoxShadow(

color: Colors.black26,

blurRadius: 10,

offset: Offset(2, 2),

),

],

),

child: Center(

child: Text(

'Container',

style: TextStyle(color: Colors.white, fontSize: 24),

),

),

),

),

);

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

Card Widget

import 'package:flutter/material.dart';

void main() {

runApp(MyApp());

class MyApp extends StatelessWidget {

@override

Widget build(BuildContext context) {

return MaterialApp(

home: Abc();

);

class Abc extends StatelessWidget {

const Abc({super.key});

@override

Widget build(BuildContext context) {

return Scaffold(

appBar: AppBar(title: Text('Card Widget Example')),

body: Center(

child: Card(

elevation: 5, // The shadow effect of the

card shape: RoundedRectangleBorder(

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

borderRadius: BorderRadius.circular(10), // Rounded corners

),

child: Container(

width: 300,

height: 150,

padding: EdgeInsets.all(16),

child: Column(

mainAxisAlignment: MainAxisAlignment.center,

children: [

Text(

'Card Title',

style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),

),

SizedBox(height: 10),

Text(

'This is a card description. Cards can be used to display related information.',

textAlign: TextAlign.center,

style: TextStyle(fontSize: 16),

),

],

),

),

),

),

);

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

2 b) Implement different layout structures using


Row, Column, and Stack widgets.
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('Row, Column, and Stack Example')),

body: Padding(

padding: const EdgeInsets.all(16.0),

child: Column(

children: [

Card(

elevation: 5,

shape: RoundedRectangleBorder(

borderRadius: BorderRadius.circular(10),

),

child: Container(

width: double.infinity,

padding: EdgeInsets.all(16),

child: Column(

crossAxisAlignment: CrossAxisAlignment.start,

children: [

Text(

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

'Card with Row, Column, and Stack',

style: TextStyle(fontSize: 24, fontWeight:


FontWeight.bold),

),

SizedBox(height: 10),

Stack(

children: [

Container(

width: double.infinity,

height: 150,

decoration:

BoxDecoration( color:

Colors.blue[100],

borderRadius: BorderRadius.circular(10),

),

),

Positioned(

top: 20,

left: 20,

child: Text(

'Stacked Text',

style: TextStyle(fontSize: 20, color:


Colors.blue[800]),),),

Positioned(

bottom: 20,

right: 20,

child: Icon(Icons.star, size: 40, color:


Colors.blue[800]),

),

],

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

),

SizedBox(height: 20),

Row(

mainAxisAlignment: MainAxisAlignment.spaceEvenly,

children: [

Icon(Icons.favorite, size: 30, color: Colors.red),

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

Icon(Icons.share, size: 30, color: Colors.green),

],),],),),),],),),),);}}

Explain the concept of null safety in Dart.

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

Null safety in Dart ensures that no variable can contain a null value unless it
is explicitly declared as nullable using a question mark (e.g., int?). This
helps to prevent null reference errors and improves code safety and
reliability.

31. What are the data types available in Dart?

Dart supports various data types including int, double, String, bool,
List, Map, Set, and more.

32. How do you define a class in Dart?

A class in Dart is defined using the class keyword, for example: class MyClass
{ /* class members */ }.

33. What is the difference between final and const in Dart?

final variables are initialized at runtime and can only be set once.
const variables are compile-time constants and are initialized
at compile-time.

34. What is a constructor in Dart?

A constructor is a special method of a class that is called when an


instance of the class is created. It is used to initialize the object's
properties.

35. How do you handle exceptions in Dart?

Exceptions in Dart are handled using try, catch, and finally blocks.
The try block contains code that may throw an exception, catch

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

handles the exception, and finally contains code that runs regardless of
whether an exception occurred.

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

36. What are Records?

Records are an anonymous, immutable, aggregate type. Like other


collection types, they let you bundle multiple objects into a single
object. Unlike other collection types, records are fixed-sized,
heterogeneous, and typed.

37. Write the record Syntax?

var record = ('first', a: 2, b: true, 'last');

38. How to create an empty String list in Dart?

var elements = <String>{};

39. How to use a generic method in Dart?

T first<T>(List<T> ts) {

// Do some initial work or error checking, then...

T tmp = ts[0]; // Do some additional processing... return

tmp;

40. List Built-in Types in Dart.


○ Numbers (int, double)
○ Strings (String)
○ Booleans (bool)
○ Records ((value1, value2))
○ Lists (List, also known as arrays)

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

○ Sets (Set)
○ Maps (Map)
○ Runes (Runes; often replaced by the characters API)
○ Symbols (Symbol)
○ The value null (Null)
41. How do you import the dart math library?

// Importing core libraries

import 'dart:math';

42. What is the purpose of the null-aware operator (??) in


Dart? The null-aware operator (??) returns the value on its left if it
is not null; otherwise, it returns the value on its right.
43. How does the null-aware assignment operator (??=) work
in Dart?
The null-aware assignment operator (??=) assigns a value to a variable
only if that variable is currently null.
44. What does the conditional member access operator (?.) do
in Dart?
The conditional member access operator (?.) allows you to call
methods or access properties on an object only if that object is not
null.
45. How is the cascade operator (..) used in Dart?

The cascade operator (..) allows you to make a sequence of operations


on the same object, returning the object itself at the end.

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

46. What is the build method in Flutter?

The build method in Flutter is used to describe how to display the


widget in terms of other lower-level widgets. It is called whenever the
widget's configuration changes.

47. How do you navigate between screens in Flutter?

Navigation between screens in Flutter is managed using the


Navigator widget, with methods like push, pop, pushReplacement,
and popUntil.

48. What is a Container widget in Flutter?

A Container widget in Flutter is a versatile widget that can contain


other widgets and apply padding, margins, borders, and background
color.

49. What is setState in Flutter?

setState is a method used in a StatefulWidget to update the state of


the widget and trigger a rebuild of the UI.

50. What is a Stream in Flutter?

A Stream is a sequence of asynchronous events. It is used to handle


asynchronous data, such as data received from a network request or
user input over time.

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

51. How do you add external packages to a Flutter project?


External packages are added to a Flutter project by specifying
them in the dependencies section of the pubspec.yaml file and
running flutter pub get.
52. What is hot reload in Flutter?

Hot reload is a feature in Flutter that allows you to quickly see


changes in your code by preserving the app's state and injecting
updated code into the running app.

53. How do you handle user input in Flutter?

User input in Flutter is handled using widgets like TextField for text
input, and GestureDetector for handling gestures like taps and swipes.

54. What is the MaterialApp widget?

MaterialApp is a widget that wraps several widgets that are


commonly required for Material Design applications. It provides an
easy way to set up the basic structure of a Flutter app.

55. What is a Scaffold widget?

The Scaffold widget provides a framework for implementing the


basic visual layout structure of the Material Design layout, including
the app bar, drawer, and bottom navigation bar.

56. What is the purpose of the pubspec.yaml file in a Flutter


project?

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

The pubspec.yaml file is used to define the project's dependencies,


assets, and metadata. It specifies the packages and plugins that the
project depends on, as well as other configurations such as the
project's version and description. This file is essential for managing
and organizing the project's resources and dependencies.

57. What is MediaQuery used for in Flutter, and how can you
use it to make a widget responsive?

MediaQuery provides information about the screen's size and other


display characteristics. You can use it to adjust a widget’s dimensions
or layout based on the screen size, such as setting a widget’s width to
a percentage of the screen width.

58. What is the purpose of using LayoutBuilder in Flutter?

LayoutBuilder allows you to build widgets based on the constraints


passed down by their parent, enabling responsive designs that adapt
to different screen sizes or orientations.

59. How can Flexible and Expanded widgets help in creating


responsive layouts?

Flexible and Expanded widgets help by allowing child widgets to


adjust their sizes relative to available space, making it easier to create
layout
60. What does the AspectRatio widget do in Flutter?

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

The AspectRatio widget ensures that a child widget maintains a


specific aspect ratio, helping to create responsive designs that preserve
proportions across different screen sizes.

61. How can MediaQuery be used to adjust font sizes in a


responsive design?

MediaQuery can be used to get the screen size and adjust font sizes
proportionally, ensuring that text remains readable across different device
sizes and orientations.

Experiment 3:
a) Design a responsive UI that adapts to different screen sizes.
import 'package:flutter/material.dart';

void main() {

runApp(MyApp());

class MyApp extends StatelessWidget

{ @override

Widget build(BuildContext context)

{ return MaterialApp(

home: ResponsiveLayout(),

);

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

class ResponsiveLayout extends StatelessWidget {

@override

Widget build(BuildContext context) {

return Scaffold(

appBar: AppBar(title: Text('Responsive UI Example')),

body: Column(

children: [

Expanded(

flex: 2,

child: Container(

color: Colors.blue,

child: Center(

child: Text(

'Header',

style: TextStyle(color: Colors.white, fontSize: 24),

),

),

),

),

Expanded( fle

x: 8, child:

Row(

children: [

Expanded(

flex: 3,

child: Container(

color: Colors.green,

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

child: Column(

children: [

Expanded(

flex: 1,

child: Container(

color: Colors.green[700],

child: Center(

child: Text(

'Menu Item

1',

style: TextStyle(color: Colors.white, fontSize: 18),

),

),

),

),

Expanded(

flex: 1,

child: Container(

color: Colors.green[500],

child: Center(

child: Text(

'Menu Item

2',

style: TextStyle(color:Colors.white,fontSize: 18),

),

),

),

),

Expanded(

flex: 1,

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

child: Container(

color: Colors.green[300],

child: Center(

child: Text(

'Menu Item

3',

style: TextStyle(color: Colors.white, fontSize: 18),

),

),

),

),

],

),

),

),

Expanded(

flex: 7,

child: Container(

color: Colors.orange,

child: Center(

child: Text(

'Main Content',

style: TextStyle(color: Colors.white, fontSize: 24),

),

),

),

),

],

),

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

),

Expanded( flex: 2,
child: Container( color: Colors.red, child: Center(
child: Text(

'Footer',

style: TextStyle(color: Colors.white, fontSize: 24),

),

),

),),],),);}}

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

3 b) Implement media queries and breakpoints


for responsiveness.
import 'package:flutter/material.dart';

void main() {

runApp(MyApp());

class MyApp extends StatelessWidget {

@override

Widget build(BuildContext context) {

return MaterialApp(

home: ResponsiveContainer(),

);

class ResponsiveContainer extends StatelessWidget {

@override

Widget build(BuildContext context) {

// Get the screen size using MediaQuery

final screenSize = MediaQuery.of(context).size;

final screenWidth = screenSize.width;

final screenHeight = screenSize.height;

// Determine container size based on screen

width double containerWidth;

double containerHeight;

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

if (screenWidth < 600) {

// Small screen size (e.g., mobile phones)

containerWidth = screenWidth * 0.8; // 80% of screen width

containerHeight = screenHeight * 0.3; // 30% of screen

height

} else {

// Larger screen size (e.g., tablets or desktops)

containerWidth = screenWidth * 0.5; // 50% of screen width

containerHeight = screenHeight * 0.4; // 40% of screen

height

return Scaffold(

appBar: AppBar(title: Text('Responsive Container Example')),

body: Center(

child: Container(

width: containerWidth,

height: containerHeight,

color: Colors.blue,

child: Center(

child: Text(

'Responsive Container',

style: TextStyle(

color: Colors.white,

fontSize: 24,

fontWeight: FontWeight.bold,

),),),),),);}}

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

1. What are Records?

Records are an anonymous, immutable, aggregate type. Like other


collection types, they let you bundle multiple objects into a single
object. Unlike other collection types, records are fixed-sized,
heterogeneous, and typed.

2. Write the record Syntax?

var record = ('first', a: 2, b: true, 'last');

3. How to create an empty String list in Dart?

var elements = <String>{};

4. How to use a generic method in Dart?

T first<T>(List<T> ts) {

// Do some initial work or error checking, then...

T tmp = ts[0]; // Do some additional processing... return

tmp;

5. List Built-in Types in Dart.


a. Numbers (int, double)
b. Strings (String)
c. Booleans (bool)
d. Records ((value1, value2))
e. Lists (List, also known as arrays)

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

f. Sets (Set)
g. Maps (Map)
h. Runes (Runes; often replaced by the characters API)
i. Symbols (Symbol)
j. The value null (Null)
6. How do you import the dart math library?

// Importing core libraries

import 'dart:math';

7. What is the purpose of the null-aware operator (??) in Dart?


The null-aware operator (??) returns the value on its left if it is
not null; otherwise, it returns the value on its right.
8. How does the null-aware assignment operator (??=) work in Dart?
The null-aware assignment operator (??=) assigns a value to a variable
only if that variable is currently null.
9. What does the conditional member access operator (?.) do in Dart?
The conditional member access operator (?.) allows you to call
methods or access properties on an object only if that object is not
null.
10. How is the cascade operator (..) used in Dart?
The cascade operator (..) allows you to make a sequence of operations
on the same object, returning the object itself at the end.

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

11. What is the purpose of the spread operator (...) in Dart?


The spread operator (...) is used to insert multiple values into a
collection.
12. How does the null-aware spread operator (...?) differ from
the spread operator in Dart?
The null-aware spread operator (...?) is used to insert multiple values
into a collection only if the provided collection is not null.

13. What is the function of the type test operator (is) in


Dart? The type test operator (is) checks if an object is of a
specific type, returning true or false.
14. What does the type cast operator (as) do in Dart?
The type cast operator (as) is used to cast an object to a specific type.

15. How can the ?. operator be useful in Dart when


dealing with potentially null values?
The ?. operator allows you to safely access properties or methods on
objects that might be null, preventing runtime errors.

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

16. What does the ! operator do in Dart when used after a


variable? The ! operator, when used after a variable, asserts that
the variable is not null, allowing you to access it as a non-null
value.
17. What is hot reload in Flutter?

Hot reload is a feature in Flutter that allows you to quickly see


changes in your code by preserving the app's state and injecting
updated code into the running app.

18. How do you handle user input in Flutter?

User input in Flutter is handled using widgets like TextField for text
input, and GestureDetector for handling gestures like taps and swipes.

19. What is the MaterialApp widget?

MaterialApp is a widget that wraps several widgets that are


commonly required for Material Design applications. It provides an
easy way to set up the basic structure of a Flutter app.

20. What is a Scaffold widget?

The Scaffold widget provides a framework for implementing the


basic visual layout structure of the Material Design layout, including
the app bar, drawer, and bottom navigation bar.

21. What is the purpose of the pubspec.yaml file in a Flutter


project?

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

The pubspec.yaml file is used to define the project's dependencies,


assets, and metadata. It specifies the packages and plugins that the
project depends on, as well as other configurations such as the
project's version and description. This file is essential for managing
and organizing the project's resources and dependencies.

22. What is MediaQuery used for in Flutter, and how can you
use it to make a widget responsive?

MediaQuery provides information about the screen's size and other


display characteristics. You can use it to adjust a widget’s dimensions
or layout based on the screen size, such as setting a widget’s width to
a percentage of the screen width.

23. What is the purpose of using LayoutBuilder in Flutter?

LayoutBuilder allows you to build widgets based on the constraints


passed down by their parent, enabling responsive designs that adapt
to different screen sizes or orientations.

24. How can Flexible and Expanded widgets help in creating


responsive layouts?

Flexible and Expanded widgets help by allowing child widgets to


adjust their sizes relative to available space, making it easier to create
layouts that adapt to different screen sizes.

25. What does the AspectRatio widget do in Flutter?

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

The AspectRatio widget ensures that a child widget maintains a


specific aspect ratio, helping to create responsive designs that preserve
proportions across different screen sizes.

26. How can MediaQuery be used to adjust font sizes in a


responsive design?

MediaQuery can be used to get the screen size and adjust font sizes
proportionally, ensuring that text remains readable across different device
sizes and orientations.

27. What is the difference between MediaQuery and


LayoutBuilder in handling responsive layouts?

MediaQuery provides information about the overall screen size,


while LayoutBuilder gives constraints specific to the widget’s parent,
allowing for more localized adjustments in responsive design.

28. How does the Row widget arrange its children, and
when would you use it?

The Row widget arranges its children horizontally in a line. It’s used
when you want to place widgets side by side, such as aligning buttons
or text elements horizontally.

29. What is the main difference between Row and Column


widgets in Flutter?

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

The Row widget arranges its children horizontally, while the Column
widget arranges its children vertically. Use Row for horizontal layouts
and Column for vertical layouts.

30. How can the Expanded widget be used within a Column to


make child widgets take up available space?

The Expanded widget allows a child widget in a Column to occupy


the remaining available space, ensuring that the widget sizes
dynamically adjust based on the space left by other widgets.

31. What does the Stack widget do, and when would you use it in
a layout?

The Stack widget overlays its children on top of each other, with
each child positioned relative to the stack's boundaries. It’s used when
you need to layer widgets, such as placing text over an image.
Experiment 4:

a) Set up navigation between different screens


using Navigator.
import 'package:flutter/material.dart';

void main() {

runApp(MyApp());

class MyApp extends StatelessWidget {

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

@override

Widget build(BuildContext context) {

return MaterialApp(

title: 'Navigation Example',

theme: ThemeData(

primarySwatch: Colors.blue,

),

home: HomeScreen(),

);

class HomeScreen extends StatelessWidget {

@override

Widget build(BuildContext context) {

return Scaffold(

appBar: AppBar(

title: Text('Home Screen'),

),

body: Center(

child: ElevatedButton(

onPressed: () {

Navigator.push(

context,

MaterialPageRoute(builder: (context) => DetailsScreen()),

);

},

child: Text('Go to Details Screen'),

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

),

),

);

class DetailsScreen extends StatelessWidget {

@override

Widget build(BuildContext context) { return Scaffold(


appBar: AppBar(

title: Text('Details Screen'),

),

body: Center(

child: ElevatedButton( onPressed: () {


Navigator.pop(context);

},

child: Text('Back to Home Screen'),

),),);}}

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

4 b) Implement navigation with named routes.


import 'package:flutter/material.dart';

void main() {

runApp(MyApp());

class MyApp extends StatelessWidget {

@override

Widget build(BuildContext context) {

return MaterialApp(

title: 'Named Routes Example',

theme: ThemeData(

primarySwatch: Colors.blue,

),

initialRoute: '/',

routes: {

'/': (context) => HomeScreen(),

'/details': (context) =>

DetailsScreen(),

},

);

class HomeScreen extends StatelessWidget {

@override

Widget build(BuildContext context) {

return Scaffold(

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

appBar: AppBar(

title: Text('Home Screen'),

),

body: Center(

child: ElevatedButton(

onPressed: () {

Navigator.pushNamed(context, '/details');

},

child: Text('Go to Details Screen'),

),

),

);

class DetailsScreen extends StatelessWidget {

@override

Widget build(BuildContext context) {

return Scaffold(

appBar: AppBar(

title: Text('Details Screen'),

),

body: Center(

child: ElevatedButton(

onPressed: () {

Navigator.pop(context);

},

child: Text('Back to Home Screen'),),),);}}

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

VIVA QUESTIONS:
1. What is the purpose of the null-aware operator (??) in Dart?
The null-aware operator (??) returns the value on its left if it is
not null; otherwise, it returns the value on its right.
2. How does the null-aware assignment operator (??=) work in Dart?
The null-aware assignment operator (??=) assigns a value to a variable
only if that variable is currently null.

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

3. What does the conditional member access operator (?.) do in Dart?


The conditional member access operator (?.) allows you to call
methods or access properties on an object only if that object is not
null.
4. How is the cascade operator (..) used in Dart?
The cascade operator (..) allows you to make a sequence of operations
on the same object, returning the object itself at the end.
5. What is the purpose of the spread operator (...) in Dart?
The spread operator (...) is used to insert multiple values into a
collection.
6. How does the null-aware spread operator (...?) differ
from the spread operator in Dart?
The null-aware spread operator (...?) is used to insert multiple values
into a collection only if the provided collection is not null.

7. What is the function of the type test operator (is) in Dart?


The type test operator (is) checks if an object is of a specific
type, returning true or false.
8. What does the type cast operator (as) do in Dart?
The type cast operator (as) is used to cast an object to a specific type.

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

9. How can the ?. operator be useful in Dart when


dealing with potentially null values?
The ?. operator allows you to safely access properties or methods on
objects that might be null, preventing runtime errors.

10. What does the ! operator do in Dart when used after a


variable? The ! operator, when used after a variable, asserts that
the variable is not null, allowing you to access it as a non-null
value.
11. How can MediaQuery be used to adjust font sizes in a
responsive design?

MediaQuery can be used to get the screen size and adjust font sizes
proportionally, ensuring that text remains readable across different device
sizes and orientations.

12. What is the difference between MediaQuery and


LayoutBuilder in handling responsive layouts?

MediaQuery provides information about the overall screen size,


while LayoutBuilder gives constraints specific to the widget’s parent,
allowing for more localized adjustments in responsive design.

13. How does the Row widget arrange its children, and
when would you use it?

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

The Row widget arranges its children horizontally in a line. It’s used
when you want to place widgets side by side, such as aligning buttons
or text elements horizontally.

14. What is the main difference between Row and Column


widgets in Flutter?

The Row widget arranges its children horizontally, while the Column
widget arranges its children vertically. Use Row for horizontal layouts
and Column for vertical layouts.

15. How can the Expanded widget be used within a Column to


make child widgets take up available space?

The Expanded widget allows a child widget in a Column to occupy


the remaining available space, ensuring that the widget sizes
dynamically adjust based on the space left by other widgets.

16. What does the Stack widget do, and when would you use it in
a layout?

The Stack widget overlays its children on top of each other, with
each child positioned relative to the stack's boundaries. It’s used when
you need to layer widgets, such as placing text over an image.

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

17. How can you control the positioning of children within a Stack?

You control positioning in a Stack using the Positioned widget,


which allows you to specify exact coordinates or relative offsets for
each child within the stack.

18. What is the purpose of the Align widget when used inside
a Stack?

The Align widget inside a Stack helps position a child widget


according to alignment properties, such as center, top-right,
or bottom-left, without using explicit positioning.

19. How do Row and Column widgets handle overflow


when their content exceeds available space?

By default, Row and Column widgets will overflow if their content


exceeds the available space. To handle overflow, you can use Flexible,
Expanded, or SingleChildScrollView to manage or scroll the content.

20. How does the Navigator widget manage navigation between


screens in Flutter?

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

The Navigator widget manages navigation by maintaining a stack of


Route objects. You can push a new route onto the stack to navigate
to a new screen and pop a route off the stack to return to a previous
screen.

21. What is the difference between named routes


and unnamed (anonymous) routes in Flutter?
Named routes are registered with the Navigator using a unique
string identifier and are accessed by name, making navigation more
manageable and readable. Unnamed routes are created directly within
the code without a specific name and are generally used for simple
navigation scenarios.

22. How do you define and use a named route in a


Flutter application?
You define a named route by adding it to the routes table in the
MaterialApp or CupertinoApp widget. You can then navigate
to this route using Navigator.pushNamed(context,
'routeName').

23. How can you pass data between routes using unnamed routes?
Data can be passed between unnamed routes by using the
Navigator.push method and providing arguments to the route’s

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

constructor. For example,


Navigator.push(context,
MaterialPageRoute(builder: (context) =>

SecondPage(data: 'someData'))), where SecondPage can receive the


data through its constructor.

24. What is the role of the RouteSettings class in Flutter's


navigation system?
The RouteSettings class holds information about the route,
including its name and arguments. This information can be accessed
within the route’s widget to manage navigation and pass data between
screens.

25. What is the purpose of the setState method in Flutter?


The setState method is used to notify the framework that the
internal state of a widget has changed, causing the widget to rebuild
with the new state.

26. How does the setState method impact the widget tree?
Calling setState triggers a rebuild of the widget tree, updating the UI to
reflect the new state.

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

27. What is the Provider package used for in Flutter?


The Provider package is used for state management by allowing data
to be shared and accessed across different parts of the widget tree without
the need for manual prop drilling.

28. How do you define a ChangeNotifier in Flutter using the


Provider package?

class MyModel extends ChangeNotifier { int

_count = 0;

int get count => _count; void

increment() {

_count++; notifyListeners();

29. How do you provide a ChangeNotifier to the widget


tree using Provider?

void main() {

runApp(

ChangeNotifierProvider(

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

create: (context) => MyModel(),

child: MyApp(),

),

);

30. How do you access the provided data in a widget


using Provider?

@override

Widget build(BuildContext context) {

final model = Provider.of<MyModel>(context);

return Text('Count: ${model.count}');

Experiment 5:
a) Learn about stateful and stateless widgets.

Stateless Widgets

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

StatelessWidget is used when the part of the UI you are building does not change. Stateless
widgets are immutable, meaning their properties cannot change once they are created. They
are ideal for static content that doesn’t depend on any dynamic data.

StatelessWidget is used when the part of the UI you are building does not change. Stateless
widgets are immutable, meaning their properties cannot change once they are created. They
are ideal for static content that doesn’t depend on any dynamic data.

class Abc extends StatelessWidget

{ const Abc({super.key});

@override

Widget build(BuildContext context)

{ return const Placeholder();

Stateful Widgets

StatefulWidget is used when the part of the UI you are building can change
dynamically. Stateful widgets are mutable and can maintain state that changes over time.
This is useful for interactive elements where the appearance or behavior of the widget
depends on user input or other factors.

A StatefulWidget consists of two classes:

1. The StatefulWidget class: This is immutable and creates an instance of the


State class.
2. The State class: This is where the mutable state is maintained and updated.

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

class Abc extends StatefulWidget

{ const Abc({super.key});

@override

State<Abc> createState() => _AbcState();

class _AbcState extends State<Abc>

{ @override

Widget build(BuildContext context)

{ return const Placeholder();

For better understanding of StatefulWidget, take a look at this below example

import 'package:flutter/material.dart';

void main() {

runApp(MyApp());

class MyApp extends StatelessWidget

{ @override

Widget build(BuildContext context)

{ return MaterialApp(

title: 'StatefulWidget Example',

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

theme: ThemeData(

primarySwatch:

Colors.blue,

),

home: CounterScreen(),

);

class CounterScreen extends StatefulWidget {

@override

_CounterScreenState createState() => _CounterScreenState();

class _CounterScreenState extends State<CounterScreen> {

int _counter = 0; // State variable to keep track of the counter value

void _incrementCounter() {

setState(() {

_counter++; // Update the state

});

@override

Widget build(BuildContext context) {

return Scaffold(

appBar: AppBar(

title: Text('Counter App'),

),

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

body: Center(

child: Column(

mainAxisAlignment: MainAxisAlignment.center,

children: <Widget>[

Text(

'You have pushed the button this many

times:', style: TextStyle(fontSize: 20),

),

Text(

'$_counter', // Display the current counter value

style: TextStyle(fontSize: 48, fontWeight: FontWeight.bold),

),

],

),

),

floatingActionButton: FloatingActionButton(

onPressed: _incrementCounter, // Increment counter when button is


pressed

tooltip: 'Increment',

child: Icon(Icons.add),

),

);

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

5 b) Implement state management using set State


and Provider.
State Management Techniques:

● Local State Management: Managing state within a single widget or a


small part of the widget tree.
class CounterScreen extends StatefulWidget

{ @override

_CounterScreenState createState() => _CounterScreenState();

class _CounterScreenState extends State<CounterScreen> {

int _counter = 0;

void _incrementCounter()

{ setState(() {

_counter++;

});

@override

Widget build(BuildContext context)

{ return Scaffold(

appBar: AppBar(title:

Text('Counter')), body: Center(

child: Column(

mainAxisAlignment: MainAxisAlignment.center,

children: <Widget>[

Text('Count: $_counter'),

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

ElevatedButton(onPressed: _incrementCounter, child:


Text('Increment')),],),),);}}

● Global State Management: Managing state that needs to be accessed


and updated across multiple widgets or the entire application.
import 'package:flutter/material.dart';

import 'package:provider/provider.dart';

// Define the CounterModel with

ChangeNotifier class CounterModel with

ChangeNotifier {

int _counter = 0;

int get counter => _counter;

void increment() {

_counter++;

notifyListeners(); // Notify listeners to rebuild

void main()

{ runApp(

ChangeNotifierProvider(

create: (context) =>

CounterModel(), child: MyApp(),

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

);

class MyApp extends StatelessWidget {

@override

Widget build(BuildContext context) {

return MaterialApp(

title: 'Provider Example',

home: CounterScreen(),

);

class CounterScreen extends StatelessWidget {

@override

Widget build(BuildContext context) {

return Scaffold(

appBar: AppBar(title: Text('Provider Example')),

body: Center(

child: Column(

mainAxisAlignment: MainAxisAlignment.center,

children: <Widget>[

// Use Consumer to listen to changes in

CounterModel Consumer<CounterModel>(

builder: (context, counterModel, child)

{ return Text(

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

'Count: ${counterModel.counter}',

style: TextStyle(fontSize: 48, fontWeight: FontWeight.bold),

);

},

),

SizedBox(height: 20),

ElevatedButton(

onPressed: () {

// Update the state using Provider

Provider.of<CounterModel>(context, listen: false).increment();

},

child: Text('Increment'),

),

],

),

),

);

To add the provider package to your Flutter project, follow these steps:

1. Add provider to pubspec.yaml

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

1. Open your Flutter project in your preferred IDE or text editor.


2. Locate the pubspec.yaml file in the root directory of your project.

Under the dependencies section, add provider along with the version number. As of
the last update, the latest version is 6.0.0, but you should check pub.dev for the latest
version.
yaml
Copy code

Dependencies:
flutter:

sdk: flutter

# The following adds the Cupertino Icons font to your application.

# Use with the CupertinoIcons class for iOS style icons.

cupertino_icons: ^1.0.6

provider: ^6.0.0 #Add This

3. Save the pubspec.yaml file.

2. Install the Package

To install the new package, run the following command in the terminal

flutter pub get

This command will fetch the provider package and add it to your project.

3. Import the Provider Package

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

In your Dart files where you need to use Provider, import it at the top of the file:

dart
import 'package:provider/provider.dart';

Output for State Management using Provider:

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

1. How do you import the dart math library?

// Importing core libraries

import 'dart:math';

2. What is the purpose of the null-aware operator (??) in Dart?


The null-aware operator (??) returns the value on its left if it is
not null; otherwise, it returns the value on its right.
3. How does the null-aware assignment operator (??=) work in Dart?
The null-aware assignment operator (??=) assigns a value to a variable
only if that variable is currently null.
4. What does the conditional member access operator (?.) do in Dart?
The conditional member access operator (?.) allows you to call
methods or access properties on an object only if that object is not
null.
5. How is the cascade operator (..) used in Dart?
The cascade operator (..) allows you to make a sequence of operations
on the same object, returning the object itself at the end.
6. What is the purpose of the spread operator (...) in Dart?
The spread operator (...) is used to insert multiple values into a
collection.
7. How does the null-aware spread operator (...?) differ
from the spread operator in Dart?

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

The null-aware spread operator (...?) is used to insert multiple values


into a collection only if the provided collection is not null.

8. What is the function of the type test operator (is) in Dart?


The type test operator (is) checks if an object is of a specific
type, returning true or false.
9. What does the type cast operator (as) do in Dart?
The type cast operator (as) is used to cast an object to a specific type.

10. How can the ?. operator be useful in Dart when


dealing with potentially null values?
The ?. operator allows you to safely access properties or methods on
objects that might be null, preventing runtime errors.

11. What does the ! operator do in Dart when used after a


variable? The ! operator, when used after a variable, asserts that
the variable is not null, allowing you to access it as a non-null
value.
12. What is the MaterialApp widget?

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

MaterialApp is a widget that wraps several widgets that are


commonly required for Material Design applications. It provides an
easy way to set up the basic structure of a Flutter app.

13. What is a Scaffold widget?

The Scaffold widget provides a framework for implementing the


basic visual layout structure of the Material Design layout, including
the app bar, drawer, and bottom navigation bar.

14. What is the purpose of the pubspec.yaml file in a Flutter


project?

The pubspec.yaml file is used to define the project's dependencies,


assets, and metadata. It specifies the packages and plugins that the
project depends on, as well as other configurations such as the
project's version and description. This file is essential for managing
and organizing the project's resources and dependencies.

15. What is MediaQuery used for in Flutter, and how can you
use it to make a widget responsive?

MediaQuery provides information about the screen's size and other


display characteristics. You can use it to adjust a widget’s dimensions
or layout based on the screen size, such as setting a widget’s width to
a percentage of the screen width.

16. What is the purpose of using LayoutBuilder in Flutter?

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

LayoutBuilder allows you to build widgets based on the constraints


passed down by their parent, enabling responsive designs that adapt to
different screen sizes or orientations.

17. How can Flexible and Expanded widgets help in creating


responsive layouts?

Flexible and Expanded widgets help by allowing child widgets to


adjust their sizes relative to available space, making it easier to create
layouts that adapt to different screen sizes.

18. What does the AspectRatio widget do in Flutter?

The AspectRatio widget ensures that a child widget maintains a


specific aspect ratio, helping to create responsive designs that preserve
proportions across different screen sizes.

19. How can MediaQuery be used to adjust font sizes in a


responsive design?

MediaQuery can be used to get the screen size and adjust font sizes
proportionally, ensuring that text remains readable across different device
sizes and orientations.

20. What is the difference between MediaQuery and


LayoutBuilder in handling responsive layouts?

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

MediaQuery provides information about the overall screen size,


while LayoutBuilder gives constraints specific to the widget’s parent,
allowing for more localized adjustments in responsive design.

21. How does the Row widget arrange its children, and
when would you use it?

The Row widget arranges its children horizontally in a line. It’s used
when you want to place widgets side by side, such as aligning buttons
or text elements horizontally.

22. What is the main difference between Row and Column


widgets in Flutter?

The Row widget arranges its children horizontally, while the Column
widget arranges its children vertically. Use Row for horizontal layouts
and Column for vertical layouts.

23. How can the Expanded widget be used within a Column to


make child widgets take up available space?

The Expanded widget allows a child widget in a Column to occupy


the remaining available space, ensuring that the widget sizes
dynamically adjust based on the space left by other widgets.

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

24. What does the Stack widget do, and when would you use it in
a layout?

The Stack widget overlays its children on top of each other, with
each child positioned relative to the stack's boundaries. It’s used when
you need to layer widgets, such as placing text over an image.

25. How can you control the positioning of children within a Stack?

You control positioning in a Stack using the Positioned widget,


which allows you to specify exact coordinates or relative offsets for
each child within the stack.

26. What is the purpose of the Align widget when used inside
a Stack?

The Align widget inside a Stack helps position a child widget


according to alignment properties, such as center, top-right,
or bottom-left, without using explicit positioning.

27. How do Row and Column widgets handle overflow


when their content exceeds available space?

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

By default, Row and Column widgets will overflow if their content


exceeds the available space. To handle overflow, you can use Flexible,
Expanded, or SingleChildScrollView to manage or scroll the content.

28. How do you declare a list in Dart?

A list in Dart can be declared using List, for example: List<int>


numbers = [1, 2, 3];.

29. What is null safety in Dart?

Null safety in Dart ensures variables cannot contain null values unless
explicitly declared as nullable using a question mark (e.g., String?).

30. What is the main difference between Row and Column


widgets in Flutter?

The Row widget arranges its children horizontally, while the Column
widget arranges its children vertically. Use Row for horizontal layouts
and Column for vertical layouts.

Experiment 6:
a) Create custom widgets for specific UI elements.
import 'package:flutter/material.dart';

void main() {

runApp(Abc());

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

class Abc extends StatelessWidget {

const Abc({super.key});

@override

Widget build(BuildContext context) {

return MaterialApp(

home: Def(),

);

class Def extends StatelessWidget {

const Def({super.key});

@override

Widget build(BuildContext context) {

return Scaffold(

body: Column(

mainAxisAlignment: MainAxisAlignment.center,

crossAxisAlignment: CrossAxisAlignment.center,

children: [

GestureDetector(

onTap: () {},

child: Center(

child: Container(

decoration: BoxDecoration(

color:

Color(0xff0174d2),

borderRadius: BorderRadius.circular(9),

),

height: 50,

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

width: MediaQuery.of(context).size.width * 0.9, child: Center(


child: Text( "Get Started",
style: TextStyle(color: Colors.white, fontSize: 20),

),),),),),],),);}}

6 b) Apply styling using themes and custom styles.


import 'package:flutter/material.dart';

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

void main() {

runApp(MyApp());

class MyApp extends StatelessWidget {

@override

Widget build(BuildContext context) {

return MaterialApp(

title: 'Flutter Demo',

theme: ThemeData.dark(),

home: MyHomePage(),

);

class MyHomePage extends StatefulWidget {

@override

_MyHomePageState createState() => _MyHomePageState();

class _MyHomePageState extends State<MyHomePage> {

int _counter = 0;

void _incrementCounter() {

setState(() {

_counter++;

});

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

@override

Widget build(BuildContext context) { return Scaffold(


appBar: AppBar(

title: Text('Counter App'),

),

body: Center(

child: Column(

mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[


Text(

'You have pushed the button this many times:',

),

Text(

'$_counter',

style: Theme.of(context).textTheme.headlineMedium,),],),), floatingActionButton: Floating


onPressed: _incrementCounter, tooltip: 'Increment',
child: Icon(Icons.add),

),);}}

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

1. Explain the concept of null safety in Dart.

Null safety in Dart ensures that no variable can contain a null value unless
it is explicitly declared as nullable using a question mark (e.g., int?). This
helps to prevent null reference errors and improves code safety and
reliability.

2. What are the data types available in Dart?

Dart supports various data types including int, double, String, bool,
List, Map, Set, and more.

3. How do you define a class in Dart?

A class in Dart is defined using the class keyword, for example: class MyClass
{ /* class members */ }.

4. What is the difference between final and const in Dart?

final variables are initialized at runtime and can only be set once.
const variables are compile-time constants and are initialized
at compile-time.

5. What is a constructor in Dart?

A constructor is a special method of a class that is called when an


instance of the class is created. It is used to initialize the object's
properties.

6. How do you handle exceptions in Dart?

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

Exceptions in Dart are handled using try, catch, and finally blocks.
The try block contains code that may throw an exception, catch
handles the exception, and finally contains code that runs regardless of
whether an exception occurred.

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

7. What are Records?

Records are an anonymous, immutable, aggregate type. Like other


collection types, they let you bundle multiple objects into a single
object. Unlike other collection types, records are fixed-sized,
heterogeneous, and typed.

8. Write the record Syntax?

var record = ('first', a: 2, b: true, 'last');

9. How to create an empty String list in Dart?

var elements = <String>{};

10. How to use a generic method in Dart?

T first<T>(List<T> ts) {

// Do some initial work or error checking, then...

T tmp = ts[0]; // Do some additional processing... return

tmp;

11. List Built-in Types in Dart.


a. Numbers (int, double)
b. Strings (String)
c. Booleans (bool)
d. Records ((value1, value2))
e. Lists (List, also known as arrays)

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

f. Sets (Set)
g. Maps (Map)
h. Runes (Runes; often replaced by the characters API)
i. Symbols (Symbol)
j. The value null (Null)

12. What is the main difference between Row and Column


widgets in Flutter?

The Row widget arranges its children horizontally, while the Column
widget arranges its children vertically. Use Row for horizontal layouts
and Column for vertical layouts.

13. How can the Expanded widget be used within a Column to


make child widgets take up available space?

The Expanded widget allows a child widget in a Column to occupy


the remaining available space, ensuring that the widget sizes
dynamically adjust based on the space left by other widgets.

14. What does the Stack widget do, and when would you use it in
a layout?

The Stack widget overlays its children on top of each other, with
each child positioned relative to the stack's boundaries. It’s used when
you need to layer widgets, such as placing text over an image.

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

15. How can you control the positioning of children within a Stack?

You control positioning in a Stack using the Positioned widget,


which allows you to specify exact coordinates or relative offsets for
each child within the stack.

16. What is the purpose of the Align widget when used inside
a Stack?

The Align widget inside a Stack helps position a child widget


according to alignment properties, such as center, top-right,
or bottom-left, without using explicit positioning.

17. How do Row and Column widgets handle overflow


when their content exceeds available space?

By default, Row and Column widgets will overflow if their content


exceeds the available space. To handle overflow, you can use Flexible,
Expanded, or SingleChildScrollView to manage or scroll the content.

18. How does the Navigator widget manage navigation between


screens in Flutter?

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

The Navigator widget manages navigation by maintaining a stack of


Route objects. You can push a new route onto the stack to navigate
to a new screen and pop a route off the stack to return to a previous
screen.

19. What is the difference between named routes


and unnamed (anonymous) routes in Flutter?
Named routes are registered with the Navigator using a unique
string identifier and are accessed by name, making navigation more
manageable and readable. Unnamed routes are created directly within
the code without a specific name and are generally used for simple
navigation scenarios.

20. How do you define and use a named route in a


Flutter application?
You define a named route by adding it to the routes table in the
MaterialApp or CupertinoApp widget. You can then navigate
to this route using Navigator.pushNamed(context,
'routeName').

21. How can you pass data between routes using unnamed routes?
Data can be passed between unnamed routes by using the
Navigator.push method and providing arguments to the route’s

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

constructor. For example,


Navigator.push(context,
MaterialPageRoute(builder: (context) =>

SecondPage(data: 'someData'))), where SecondPage can receive the


data through its constructor.

22. What is the role of the RouteSettings class in Flutter's


navigation system?
The RouteSettings class holds information about the route,
including its name and arguments. This information can be accessed
within the route’s widget to manage navigation and pass data between
screens.

23. What is the purpose of the setState method in Flutter?


The setState method is used to notify the framework that the
internal state of a widget has changed, causing the widget to rebuild
with the new state.

24. How does the setState method impact the widget tree?
Calling setState triggers a rebuild of the widget tree, updating the UI to
reflect the new state.

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

25. What is the Provider package used for in Flutter?


The Provider package is used for state management by allowing data
to be shared and accessed across different parts of the widget tree without
the need for manual prop drilling.

26. How do you define a ChangeNotifier in Flutter using the


Provider package?

class MyModel extends ChangeNotifier { int

_count = 0;

int get count => _count; void

increment() {

_count++; notifyListeners();

27. How do you provide a ChangeNotifier to the widget


tree using Provider?

void main() {

runApp(

ChangeNotifierProvider(

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

create: (context) => MyModel(),

child: MyApp(),

),

);

28. How do you access the provided data in a widget


using Provider?

@override

Widget build(BuildContext context) {

final model = Provider.of<MyModel>(context);

return Text('Count: ${model.count}');

29. How do you create a basic custom widget in Flutter?

class CustomButton extends StatelessWidget { final

String label;

final VoidCallback onPressed;

CustomButton({required this.label, required this.onPressed});

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

@override

Widget build(BuildContext context) {

return ElevatedButton(

onPressed: onPressed, child:

Text(label),

);

30. How can you pass data to a custom widget in Flutter?


Data can be passed to a custom widget through its constructor.
For example:

CustomButton(label: 'Click Me', onPressed: () => print('Button pressed'));

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

Experiment 7:
a) Design a form with various input fields.

7. b) Implement form validation and error handling.


import 'package:flutter/material.dart';

void main() {

runApp(MyApp());

class MyApp extends StatelessWidget

{ @override

Widget build(BuildContext context)

{ return MaterialApp(

home: MyForm(),);

}}

class MyForm extends StatefulWidget

{ @override

_MyFormState createState() => _MyFormState();

class _MyFormState extends State<MyForm> {

final _formKey = GlobalKey<FormState>();

final _nameController = TextEditingController();

final _emailController = TextEditingController();

final _passwordController = TextEditingController();

@override

Widget build(BuildContext context)

{ return Scaffold(

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

appBar: AppBar(

title: Text('Form Example'),

),

body: Padding(

padding: const EdgeInsets.all(16.0),

child: Form(

key: _formKey,

child: Column(

children: <Widget>[

TextFormField(

controller: _nameController,

decoration: InputDecoration(labelText:'Name'),

validator: (value) {

if (value == null || value.isEmpty)

{ return 'Please enter your

name';

return null;

},

),

TextFormField(

controller: _emailController,

decoration: InputDecoration(labelText:'Email'),

keyboardType: TextInputType.emailAddress,

validator: (value) {

if (value == null || value.isEmpty)

{ return 'Please enter your

email';

} else if (!RegExp(r'^[^@]+@[^@]+\.[^@]+').hasMatch(value))
{

return 'Please enter a valid email address';


Downloaded by Md Ateeq (mdateeq807@gmail.com)
lOMoARcPSD|58593188

return null;

},

),

TextFormField(

controller: _passwordController,

decoration: InputDecoration(labelText:'Password'),

obscureText: true,

validator: (value) {

if (value == null || value.isEmpty) {

return 'Please enter your

password';

} else if (value.length < 6) {

return 'Password must be at least 6 characters long';

return null;

},

),

SizedBox(height: 20),

ElevatedButton(

onPressed: () {

if (_formKey.currentState?.validate() ?? false) {

// If the form is valid, display a snackbar or perform


other actions

},

child: Text('Submit'),

),],),),),);}}

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

1. How do you create a basic custom widget in Flutter?

class CustomButton extends StatelessWidget { final

String label;

final VoidCallback onPressed;

CustomButton({required this.label, required this.onPressed});

@override

Widget build(BuildContext context) {

return ElevatedButton(

onPressed: onPressed, child:

Text(label),

);

2. Why would you create custom widgets in a Flutter application?


Creating custom widgets promotes code reuse, improves readability,
and allows for consistent styling and behavior across different parts
of the application.

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

3. How can you pass data to a custom widget in Flutter?


Data can be passed to a custom widget through its constructor. For
example:

CustomButton(label: 'Click Me', onPressed: () => print('Button pressed'));

4. How do you handle user interactions in a custom widget?


User interactions can be handled by defining callback functions in the
custom widget and passing them down from the parent widget. For
example:

class CustomButton extends StatelessWidget { final

String label;

final VoidCallback onPressed;

CustomButton({required this.label, required this.onPressed}); @override

Widget build(BuildContext context) {

return ElevatedButton(

onPressed: onPressed, child:

Text(label),

);

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

5. Can you create custom widgets with state in Flutter? If so, how?
Yes, you can create custom widgets with state by extending
StatefulWidget and implementing the associated State class. For
example:
class CustomCounter extends StatefulWidget { @override

_CustomCounterState createState() => _CustomCounterState();

class _CustomCounterState extends State<CustomCounter> { int

_count = 0;

void _increment() {

setState(() {

_count++;

});

@override

Widget build(BuildContext context) {

return Column(

children: [

Text('Count: $_count'),

ElevatedButton(

onPressed: _increment,

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

child: Text('Increment'),

),

],

);

6. What are the benefits of using custom widgets for


specific UI elements?
The benefits include code reuse, improved readability, easier
maintenance, consistent styling, and the ability to isolate and test
individual components independently.
7. What are the advantages of using custom widgets in
Flutter for building complex UIs?
Custom widgets allow for modular and reusable code, making it easier
to manage and maintain large codebases. They help in maintaining a
consistent look and feel across the application and promote separation
of concerns by isolating specific functionality into self- contained
components.

8. How does the StatefulWidget differ from the StatelessWidget


in Flutter, and when should each be used?
StatefulWidget is used when a widget needs to maintain mutable state
that can change over time, requiring the widget to rebuild in response
to state changes. StatelessWidget, on the other hand, is

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

used for widgets that do not require any internal state and remain
static throughout their lifecycle. Use StatefulWidget for dynamic
components like forms, counters, or animations, and StatelessWidget
for static content like text labels, icons, or layout elements.

9. What is the purpose of the AnimationController class in Flutter?


The AnimationController class is used to control the animation,
including starting, stopping, and reversing the animation. It also
provides access to the animation's current value and state.

10. How do you create an AnimationController in Flutter?

AnimationController _controller = AnimationController(

duration: const Duration(seconds: 2),

vsync: this,

);

11. What is the TickerProvider and why is it needed for


animations in Flutter?
The TickerProvider is required to create an

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

AnimationController. It provides a Ticker that signals when a


frame should be displayed, allowing Flutter to synchronize animations
with the device's refresh rate.

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

12. What is a constructor in Dart?

A constructor is a special method of a class that is called when an


instance of the class is created. It is used to initialize the object's
properties.

13. How do you handle exceptions in Dart?

Exceptions in Dart are handled using try, catch, and finally blocks.
The try block contains code that may throw an exception, catch
handles the exception, and finally contains code that runs regardless of
whether an exception occurred.

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

14. What are Records?

Records are an anonymous, immutable, aggregate type. Like other


collection types, they let you bundle multiple objects into a single
object. Unlike other collection types, records are fixed-sized,
heterogeneous, and typed.

15. Write the record Syntax?

var record = ('first', a: 2, b: true, 'last');

16. How to create an empty String list in Dart?

var elements = <String>{};

17. How to use a generic method in Dart?

T first<T>(List<T> ts) {

// Do some initial work or error checking, then...

T tmp = ts[0]; // Do some additional processing... return

tmp;

18. List Built-in Types in Dart.


a. Numbers (int, double)
b. Strings (String)
c. Booleans (bool)
d. Records ((value1, value2))
e. Lists (List, also known as arrays)

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

f. Sets (Set)
g. Maps (Map)
h. Runes (Runes; often replaced by the characters API)
i. Symbols (Symbol)
j. The value null (Null)
19. How do you import the dart math library?

// Importing core libraries

import 'dart:math';

20. What is the purpose of the null-aware operator (??) in


Dart? The null-aware operator (??) returns the value on its left if it
is not null; otherwise, it returns the value on its right.
21. How does the null-aware assignment operator (??=) work
in Dart?
The null-aware assignment operator (??=) assigns a value to a variable
only if that variable is currently null.
22. What does the conditional member access operator (?.) do
in Dart?
The conditional member access operator (?.) allows you to call
methods or access properties on an object only if that object is not
null.
23. How is the cascade operator (..) used in Dart?
The cascade operator (..) allows you to make a sequence of operations
on the same object, returning the object itself at the end.

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

24. What is the purpose of the spread operator (...) in Dart?


The spread operator (...) is used to insert multiple values into a
collection.
25. How does the null-aware spread operator (...?) differ from
the spread operator in Dart?
The null-aware spread operator (...?) is used to insert multiple values
into a collection only if the provided collection is not null.

26. What is the function of the type test operator (is) in


Dart? The type test operator (is) checks if an object is of a
specific type, returning true or false.
27. What does the type cast operator (as) do in Dart?
The type cast operator (as) is used to cast an object to a specific type.

28. How can the ?. operator be useful in Dart when


dealing with potentially null values?
The ?. operator allows you to safely access properties or methods on
objects that might be null, preventing runtime errors.

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

29. What does the ! operator do in Dart when used after a


variable? The ! operator, when used after a variable, asserts that
the variable is not null, allowing you to access it as a non-null
value.

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

30. How does the Flutter rendering process work?

The Flutter rendering process involves three main stages: layout,


painting, and compositing. During the layout stage, Flutter determines
the size and position of each widget. In the painting stage, Flutter
draws the visual representation of each widget. In the compositing
stage, Flutter combines the painted layers to create the final output on
the screen.

Experiment 8:
a) Add animations to UI elements using Flutter's
animation framework.

import 'package:flutter/material.dart';

void main() {

runApp(MyApp());

class MyApp extends StatelessWidget

{ @override

Widget build(BuildContext context)

{ return MaterialApp(

title: 'Animation

Example', theme:

ThemeData(

primarySwatch: Colors.blue,

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

home: AnimationScreen(),

);

class AnimationScreen extends StatefulWidget {

@override

_AnimationScreenState createState() => _AnimationScreenState();

class _AnimationScreenState extends State<AnimationScreen> {

bool _visible = true;

void _toggleVisibility() {

setState(() {

_visible = !_visible;

});

@override

Widget build(BuildContext context) {

return Scaffold(

appBar: AppBar(title: Text('Animation Example')),

body: Center(

child: Column(

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

mainAxisAlignment: MainAxisAlignment.center,

children: <Widget>[

AnimatedOpacity(

opacity: _visible ? 1.0 : 0.0,

duration: Duration(seconds:

1), child: Container(

width: 100,

height: 100,

color:

Colors.blue,

),

),

SizedBox(height: 20),

ElevatedButton(

onPressed: _toggleVisibility,

child: Text('Toggle

Output: Fading Animation

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

8. b) Experiment with Different Types of Animations

Here are examples of different types of animations you can experiment with: fade,
slide, and scale.

import 'package:flutter/material.dart';

void main() {

runApp(MyApp());

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

class MyApp extends StatelessWidget {

@override

Widget build(BuildContext context) {

return MaterialApp(

title: 'Animation Examples',

theme: ThemeData(

primarySwatch: Colors.blue,

),

home: AnimationExamples(),

);

class AnimationExamples extends StatefulWidget {

@override

_AnimationExamplesState createState() => _AnimationExamplesState();

class _AnimationExamplesState extends State<AnimationExamples> with SingleTickerProviderStateMixin {

late AnimationController _controller;

late Animation<double> _fadeAnimation;

late Animation<Offset> _slideAnimation;

late Animation<double>

_scaleAnimation; @override

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

void initState() {

super.initState();

_controller = AnimationController(

duration: Duration(seconds: 2),

vsync: this,

)..repeat(reverse: true);

_fadeAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(_controller);

_slideAnimation = Tween<Offset>(begin: Offset(1.0, 0.0), end: Offset.zero).animate(_controller);

_scaleAnimation = Tween<double>(begin: 0.5, end: 1.0).animate(_controller);

@override

Widget build(BuildContext context) {

return Scaffold(

appBar: AppBar(title: Text('Animation Examples')),

body: Center(

child: Column(

mainAxisAlignment: MainAxisAlignment.center,

children: <Widget>[

FadeTransition(

opacity: _fadeAnimation,

child: Container(

width: 100,

height: 100,

color: Colors.blue,

),

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

),

SizedBox(height: 20),

SlideTransition(

position: _slideAnimation,

child: Container(

width: 100,

height: 100,

color: Colors.red,

),

),

SizedBox(height: 20),

ScaleTransition(

scale: _scaleAnimation,

child: Container(

width: 100,

height: 100,

color: Colors.green,),),],),),);}

@override

void dispose() {

_controller.dispose();

super.dispose();

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

Output :

Fade
Animation
Slide
Animation

Scale Animation

1. What is Dart?

Dart is an object-oriented programming language developed by


Google, designed for building mobile, desktop, server, and web
applications.

2. What is a Future in Dart?

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

A Future represents a potential value or error that will be available at


some point in the future, commonly used in asynchronous
programming.

3. What does the async keyword do in Dart?

The async keyword is used to define a function as asynchronous,


allowing the use of await within the function to pause execution until a
Future completes.

4. How do you declare a list in Dart?

A list in Dart can be declared using List, for example: List<int>


numbers = [1, 2, 3];.

5. What is null safety in Dart?

Null safety in Dart ensures variables cannot contain null values unless
explicitly declared as nullable using a question mark (e.g., String?).

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

6. What are the key features of the Dart programming language?

Dart is an object-oriented, class-defined language that uses a C-style


syntax. It supports strong typing, asynchronous programming with
async and await, and a rich standard library. It's designed for front-
end development but can also be used for back-end and command- line
applications.

7. Explain the difference between var, final, and const in Dart.

var is used for variables whose type will be inferred at runtime. final is
used for variables that can only be set once but are initialized at
runtime. const is used for compile-time constants and variables
initialized at compile-time.

8. How does Dart handle asynchronous programming?

Dart handles asynchronous programming using Future, async, and await.


Future represents a potential value or error that will be available at
some point. async is used to declare a function as asynchronous, and
await pauses the function execution until the awaited Future
completes.

9. What are the different types of collections in Dart?

Dart provides several types of collections including List, Set, and


Map. List is an ordered collection of objects, Set is an unordered
collection of unique items, and Map is a collection of key-value pairs.

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

10. Explain the concept of null safety in Dart.

Null safety in Dart ensures that no variable can contain a null value unless
it is explicitly declared as nullable using a question mark (e.g., int?). This
helps to prevent null reference errors and improves code safety and
reliability.

11. What are the data types available in Dart?

Dart supports various data types including int, double, String, bool,
List, Map, Set, and more.

12. How do you define a class in Dart?

A class in Dart is defined using the class keyword, for example: class MyClass
{ /* class members */ }.

13. What is the difference between final and const in Dart?

final variables are initialized at runtime and can only be set once.
const variables are compile-time constants and are initialized
at compile-time.

14. How does the StatefulWidget differ from the


StatelessWidget in Flutter, and when should each be
used?
StatefulWidget is used when a widget needs to maintain mutable
state that can change over time, requiring the widget to rebuild in
response to state changes. StatelessWidget, on the other hand, is used
for widgets that do not require any internal state and remain

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

static throughout their lifecycle. Use StatefulWidget for dynamic


components like forms, counters, or animations, and StatelessWidget
for static content like text labels, icons, or layout elements.

15. What is the purpose of the AnimationController


class in Flutter?
The AnimationController class is used to control the animation,
including starting, stopping, and reversing the animation. It also
provides access to the animation's current value and state.

16. How do you create an AnimationController in Flutter?

AnimationController _controller = AnimationController(

duration: const Duration(seconds: 2),

vsync: this,

);

17. What is the TickerProvider and why is it needed for


animations in Flutter?
The TickerProvider is required to create an

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

AnimationController. It provides a Ticker that signals when a


frame should be displayed, allowing Flutter to synchronize animations
with the device's refresh rate.

18. What is the CurvedAnimation class used in Flutter?

The CurvedAnimation class is used to apply a non-linear curve to an


animation, making it more natural and fluid.

19. What is the difference between Tween and


TweenAnimationBuilder in Flutter?
Tween defines a range of values that an animation can interpolate
between. TweenAnimationBuilder simplifies the process by
managing the animation and rebuilding the widget when the animation
value changes.

20. How can you repeat an animation infinitely in Flutter?


By setting the AnimationController to repeat:

_controller.repeat();

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

21. What are Staggered Animations in Flutter and how are


they implemented?
Staggered animations involve multiple animations that start at
different times but are coordinated to create a unified effect. They can be
implemented using Interval objects to define the start and end times of
each animation segment.

22. What is the role of the Transform widget in Flutter


animations?

The Transform widget is used to apply a transformation (such as


scaling, rotating, or translating) to its child widget, which is commonly
used in animations to move or change the appearance of the widget.

23. How do you provide a ChangeNotifier to the widget


tree using Provider?

void main() {

runApp(

ChangeNotifierProvider(

create: (context) => MyModel(),

child: MyApp(),

),

);

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

24. How do you access the provided data in a widget


using Provider?

@override

Widget build(BuildContext context) {

final model = Provider.of<MyModel>(context);

return Text('Count: ${model.count}');

25. What is the difference between setState and Provider


in state management?
setState is used for managing local state within a single widget,
whereas Provider is used for managing global state that needs to be
accessed across multiple widgets in the widget tree.

26. Can you use setState and Provider together in a Flutter


application?
Yes, setState can be used for local state management within a

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

widget, while Provider can be used for global state management across
the widget tree.

27. What is a custom widget in Flutter?


A custom widget is a reusable UI component that encapsulates
specific functionality and appearance, allowing for modular and
maintainable code.

28. How do you create a basic custom widget in Flutter?

class CustomButton extends StatelessWidget { final

String label;

final VoidCallback onPressed;

CustomButton({required this.label, required this.onPressed});

@override

Widget build(BuildContext context) {

return ElevatedButton(

onPressed: onPressed, child:

Text(label),

);

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

29. Why would you create custom widgets in a Flutter


application? Creating custom widgets promotes code reuse, improves
readability, and allows for consistent styling and behavior across
different parts of the application.
30. How do you handle exceptions in Dart?

Exceptions in Dart are handled using try, catch, and finally blocks.
The try block contains code that may throw an exception, catch
handles the exception, and finally contains code that runs regardless of
whether an exception occurred.

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

Experiment 9:
a) Fetch data from a REST API.

Note: You have to get the “http” package from “pub.dev” website.
import 'package:http/http.dart' as http;

void fetchBlogs() async {

final String url = 'https://intent-kit-16.hasura.app/api/rest/blogs';

final String adminSecret =


'32qR4KmXOIpsGPQKMqEJHGJS27G5s7HdSKO3gdtQd2kv5e852SiYwWNfxkZOBuQ6';

try {

final response = await http.get(Uri.parse(url), headers:

{ 'x-hasura-admin-secret': adminSecret,

});

if (response.statusCode == 200) {

// Request successful, handle the response data here

print('Response data: ${response.body}');

} else {

// Request failed

print('Request failed with status code: ${response.statusCode}');

print('Response data: ${response.body}');

} catch (e) {

// Handle any errors that occurred during the request

print('Error: $e'); }

void main() {

fetchBlogs();

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

9 b) Display the fetched data in a meaningful way in the UI.


import 'package:flutter/material.dart';

import 'dart:convert';

import 'package:http/http.dart' as http;

void main() {

runApp(MyApp());

class MyApp extends StatelessWidget {

@override

Widget build(BuildContext context) {

return MaterialApp(

title: 'Blog App',

theme: ThemeData(

primarySwatch: Colors.blue,

),

home: BlogListScreen(),

);

class BlogListScreen extends StatefulWidget

{ @override

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

_BlogListScreenState createState() => _BlogListScreenState();

class _BlogListScreenState extends State<BlogListScreen> {

late Future<List<Blog>> futureBlogs;

@override

void initState() {

super.initState();

futureBlogs =

fetchBlogs();

@override

Widget build(BuildContext context) {

return Scaffold(

appBar: AppBar(

title:

Text('Blogs'),

),

body: FutureBuilder<List<Blog>>(

future: futureBlogs,

builder: (context, snapshot) {

if (snapshot.connectionState == ConnectionState.waiting) {

return Center(child: CircularProgressIndicator());

} else if (snapshot.hasError) {

return Center(child: Text('Error: $


{snapshot.error}'));
Downloaded by Md Ateeq (mdateeq807@gmail.com)
lOMoARcPSD|58593188

} else if (!snapshot.hasData || snapshot.data!.isEmpty) {

return Center(child: Text('No blogs available.'));

} else {

final blogs =

snapshot.data!; return

ListView.builder(

itemCount: blogs.length,

itemBuilder: (context, index) {

final blog =

blogs[index]; return

ListTile(

leading: blog.imageUrl != null

? Image.network(blog.imageUrl!)

: null,

title: Text(blog.title),

subtitle: Text(blog.content),

);

},

);

},

),

);

Future<List<Blog>> fetchBlogs() async {

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

final String url = 'https://intent-kit-16.hasura.app/api/rest/blogs';

final String adminSecret =

'32qR4KmXOIpsGPQKMqEJHGJS27G5s7HdSKO3gdtQd2kv5e852SiYwWNfxkZOBuQ6';

try {

final response = await http.get(Uri.parse(url), headers: {

'x-hasura-admin-secret': adminSecret,

});

if (response.statusCode == 200) {

final Map<String, dynamic> data = json.decode(response.body);

final List<dynamic> blogList =

data['blogs']; // Adjust this line based on your actual JSON

structure return blogList.map((json) =>

Blog.fromJson(json)).toList();

} else {

throw Exception('Failed to load blogs');

} catch (e) {

throw Exception('Error: $e');

class Blog {

final String title;

final String content;

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

final String? imageUrl;

Blog({required this.title, required this.content, this.imageUrl});

factory Blog.fromJson(Map<String, dynamic> json) { return Blog(


title: json['title'] ?? 'No Title', content: json['content'] ?? 'No Content', imageUrl:
json['image_url'], // Adjust the key based on your JSON structure

);

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

Note : https://subspace.money/blog/whatsub-single-docs-internship-onboarding-docs-
problem-statement-flutter-blog-explorer

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

1. What is the purpose of using LayoutBuilder in Flutter?

LayoutBuilder allows you to build widgets based on the constraints


passed down by their parent, enabling responsive designs that adapt to
different screen sizes or orientations.

2. How can Flexible and Expanded widgets help in


creating responsive layouts?

Flexible and Expanded widgets help by allowing child widgets to


adjust their sizes relative to available space, making it easier to create
layouts that adapt to different screen sizes.

3. What does the AspectRatio widget do in Flutter?

The AspectRatio widget ensures that a child widget maintains a


specific aspect ratio, helping to create responsive designs that preserve
proportions across different screen sizes.

4. How can MediaQuery be used to adjust font sizes in a


responsive design?

MediaQuery can be used to get the screen size and adjust font sizes
proportionally, ensuring that text remains readable across different device
sizes and orientations.

5. What is the difference between MediaQuery and LayoutBuilder


in handling responsive layouts?

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

MediaQuery provides information about the overall screen size,


while LayoutBuilder gives constraints specific to the widget’s parent,
allowing for more localized adjustments in responsive design.

6. How does the Row widget arrange its children, and when would
you use it?

The Row widget arranges its children horizontally in a line. It’s used
when you want to place widgets side by side, such as aligning buttons
or text elements horizontally.

7. What is the main difference between Row and Column widgets in


Flutter?

The Row widget arranges its children horizontally, while the Column
widget arranges its children vertically. Use Row for horizontal layouts
and Column for vertical layouts.

8. How can the Expanded widget be used within a Column to make


child widgets take up available space?

The Expanded widget allows a child widget in a Column to occupy


the remaining available space, ensuring that the widget sizes
dynamically adjust based on the space left by other widgets.

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

9. What does the Stack widget do, and when would you use it in
a layout?

The Stack widget overlays its children on top of each other, with
each child positioned relative to the stack's boundaries. It’s used when
you need to layer widgets, such as placing text over an image.

10. How can you control the positioning of children within a Stack?

You control positioning in a Stack using the Positioned widget,


which allows you to specify exact coordinates or relative offsets for
each child within the stack.

11. What is the purpose of the Align widget when used inside
a Stack?

The Align widget inside a Stack helps position a child widget


according to alignment properties, such as center, top-right,
or bottom-left, without using explicit positioning.

12. How do Row and Column widgets handle overflow


when their content exceeds available space?

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

By default, Row and Column widgets will overflow if their content


exceeds the available space. To handle overflow, you can use Flexible,
Expanded, or SingleChildScrollView to manage or scroll the content.

13. How does the Navigator widget manage navigation between


screens in Flutter?
The Navigator widget manages navigation by maintaining a stack of
Route objects. You can push a new route onto the stack to navigate
to a new screen and pop a route off the stack to return to a previous
screen.

14. What is the difference between named routes


and unnamed (anonymous) routes in Flutter?
Named routes are registered with the Navigator using a unique
string identifier and are accessed by name, making navigation more
manageable and readable. Unnamed routes are created directly within
the code without a specific name and are generally used for simple
navigation scenarios.

15. How do you define and use a named route in a


Flutter application?
You define a named route by adding it to the routes table in the

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

MaterialApp or CupertinoApp widget. You can then navigate to


this route using Navigator.pushNamed(context, 'routeName').

16. How can you pass data between routes using unnamed routes?
Data can be passed between unnamed routes by using the
Navigator.push method and providing arguments to the route’s
constructor. For example,
Navigator.push(context,
MaterialPageRoute(builder: (context) =>

SecondPage(data: 'someData'))), where SecondPage can receive the


data through its constructor.

17. What is the role of the RouteSettings class in Flutter's


navigation system?
The RouteSettings class holds information about the route,
including its name and arguments. This information can be accessed
within the route’s widget to manage navigation and pass data between
screens.

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

18. What is Dart?

Dart is an object-oriented programming language developed by


Google, designed for building mobile, desktop, server, and web
applications.

19. What is a Future in Dart?

A Future represents a potential value or error that will be available at


some point in the future, commonly used in asynchronous
programming.

20. What does the async keyword do in Dart?

The async keyword is used to define a function as asynchronous,


allowing the use of await within the function to pause execution until a
Future completes.

21. How do you declare a list in Dart?

A list in Dart can be declared using List, for example: List<int>


numbers = [1, 2, 3];.

22. What is null safety in Dart?

Null safety in Dart ensures variables cannot contain null values unless
explicitly declared as nullable using a question mark (e.g., String?).

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

23. What are the key features of the Dart programming language?

Dart is an object-oriented, class-defined language that uses a C-style


syntax. It supports strong typing, asynchronous programming with
async and await, and a rich standard library. It's designed for front-
end development but can also be used for back-end and command- line
applications.

24. Explain the difference between var, final, and const in Dart.

var is used for variables whose type will be inferred at runtime. final is
used for variables that can only be set once but are initialized at
runtime. const is used for compile-time constants and variables
initialized at compile-time.

25. How does Dart handle asynchronous programming?

Dart handles asynchronous programming using Future, async, and await.


Future represents a potential value or error that will be available at
some point. async is used to declare a function as asynchronous, and
await pauses the function execution until the awaited Future
completes.

26. What are the different types of collections in Dart?

Dart provides several types of collections including List, Set, and


Map. List is an ordered collection of objects, Set is an unordered
collection of unique items, and Map is a collection of key-value pairs.

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

27. Explain the concept of null safety in Dart.

Null safety in Dart ensures that no variable can contain a null value unless
it is explicitly declared as nullable using a question mark (e.g., int?). This
helps to prevent null reference errors and improves code safety and
reliability.

28. What are the data types available in Dart?

Dart supports various data types including int, double, String, bool,
List, Map, Set, and more.

29. How do you define a class in Dart?

A class in Dart is defined using the class keyword, for example: class MyClass
{ /* class members */ }.

30. What is the difference between final and const in Dart?

final variables are initialized at runtime and can only be set once.
const variables are compile-time constants and are initialized
at compile-time.
Experiment 10:

a) Write unit tests for UI components.

main.dart
import 'package:flutter/material.dart';

void main() {

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

runApp(MyApp());

class MyApp extends StatelessWidget {

@override

Widget build(BuildContext context) {

return MaterialApp(

title: 'Flutter Demo',

home: MyHomePage(),

);

class MyHomePage extends StatefulWidget {

@override

_MyHomePageState createState() => _MyHomePageState();

class _MyHomePageState extends State<MyHomePage> {

int _counter = 0;

void _incrementCounter() {

setState(() {

_counter++;

});

@override

Widget build(BuildContext context) {

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

return Scaffold(

appBar: AppBar(

title: Text('Flutter Demo Home Page'),

),

body: Center(

child: Column(

mainAxisAlignment: MainAxisAlignment.center,

children: <Widget>[

Text(

'You have pushed the button this many times:',

),

Text(

'$_counter',

// style: Theme.of(context).textTheme.headline,

),

],),),

floatingActionButton: FloatingActionButton(

onPressed: _incrementCounter,

tooltip: 'Increment',

child: Icon(Icons.add),

),);}}

testing.dart
import 'package:flutter/material.dart';

import 'package:flutter_test/flutter_test.dart';

import 'package:testing/main.dart';

void main() {

testWidgets('Counter increments smoke test', (WidgetTester tester) async {

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

// Build our app and trigger a frame.

await tester.pumpWidget(MyApp());

// Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget);


expect(find.text('1'), findsNothing);

// Tap the '+' icon and trigger a frame.


await tester.tap(find.byIcon(Icons.add)); await tester.pump();

// Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect


});

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

10. b) Use Flutter’s debugging tools to identify and fix issues.


Monitor the debug console for any error messages or logs. Flutter provides
detailed error messages that often include stack traces and helpful tips.

It is used for checking the flow of the Application by passing through classes, and their
functions.

1. What are the different types of collections in Dart?

Dart provides several types of collections including List, Set, and


Map. List is an ordered collection of objects, Set is an unordered
collection of unique items, and Map is a collection of key-value pairs.

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

2. Explain the concept of null safety in Dart.

Null safety in Dart ensures that no variable can contain a null value unless
it is explicitly declared as nullable using a question mark (e.g., int?). This
helps to prevent null reference errors and improves code safety and
reliability.

3. What are the data types available in Dart?

Dart supports various data types including int, double, String, bool,
List, Map, Set, and more.

4. How do you define a class in Dart?

A class in Dart is defined using the class keyword, for example: class MyClass
{ /* class members */ }.

5. What is the difference between final and const in Dart?

final variables are initialized at runtime and can only be set once.
const variables are compile-time constants and are initialized
at compile-time.

6. What is a constructor in Dart?

A constructor is a special method of a class that is called when an


instance of the class is created. It is used to initialize the object's
properties.

7. How do you handle exceptions in Dart?

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

Exceptions in Dart are handled using try, catch, and finally blocks.
The try block contains code that may throw an exception, catch
handles the exception, and finally contains code that runs regardless of
whether an exception occurred.

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

8. What are Records?

Records are an anonymous, immutable, aggregate type. Like other


collection types, they let you bundle multiple objects into a single
object. Unlike other collection types, records are fixed-sized,
heterogeneous, and typed.

9. Write the record Syntax?

var record = ('first', a: 2, b: true, 'last');

10. How to create an empty String list in Dart?

var elements = <String>{};

11. How to use a generic method in Dart?

T first<T>(List<T> ts) {

// Do some initial work or error checking, then...

T tmp = ts[0]; // Do some additional processing... return

tmp;

12. What is the purpose of unit testing in Flutter applications?


To test individual units of code, such as functions or classes, to
ensure they work as expected.

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

13. How does widget testing differ from unit testing in


Flutter? Widget testing verifies the behavior and appearance
of individual widgets, while unit testing tests logic in isolation.
14. What function is used to write widget tests in Flutter?
The testWidgets function is used to write widget tests in Flutter.

15. What package provides tools and utilities for writing


tests in Flutter?
The flutter_test package provides tools and utilities for writing tests
in Flutter.

16. What is integration testing in Flutter?


Integration testing verifies that different parts of the application work
together as expected.

17. How do you run tests in a Flutter application?


Tests can be run using the flutter test command in the terminal.

18. How can you verify the state of a widget after


a user interaction in a Flutter test?
By using the expect function with matchers to check the widget's
properties or by querying the widget tree.

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

19. Why is it important to test error states and edge cases


in Flutter applications?
To ensure the application handles unexpected situations gracefully and
provides a reliable user experience.

20. What is a common challenge in Flutter testing and how


can it be addressed?
A common challenge is flaky tests, which can be addressed by writing
stable and deterministic tests.
21. What is a Container widget in Flutter?

A Container widget in Flutter is a versatile widget that can contain


other widgets and apply padding, margins, borders, and background
color.

22. What is setState in Flutter?

setState is a method used in a StatefulWidget to update the state of


the widget and trigger a rebuild of the UI.

23. What is a Stream in Flutter?

A Stream is a sequence of asynchronous events. It is used to handle


asynchronous data, such as data received from a network request or
user input over time.

24. How do you add external packages to a Flutter project?


External packages are added to a Flutter project by specifying

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

them in the dependencies section of the pubspec.yaml file and running


flutter pub get.
25. What is hot reload in Flutter?

Hot reload is a feature in Flutter that allows you to quickly see


changes in your code by preserving the app's state and injecting
updated code into the running app.

26. How do you handle user input in Flutter?

User input in Flutter is handled using widgets like TextField for text
input, and GestureDetector for handling gestures like taps and swipes.

27. What is the MaterialApp widget?

MaterialApp is a widget that wraps several widgets that are


commonly required for Material Design applications. It provides an
easy way to set up the basic structure of a Flutter app.

28. What is a Scaffold widget?

The Scaffold widget provides a framework for implementing the


basic visual layout structure of the Material Design layout, including
the app bar, drawer, and bottom navigation bar.

29. What is the purpose of the pubspec.yaml file in a Flutter


project?

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

The pubspec.yaml file is used to define the project's dependencies,


assets, and metadata. It specifies the packages and plugins that the
project depends on, as well as other configurations such as the
project's version and description. This file is essential for managing
and organizing the project's resources and dependencies.

30. What is MediaQuery used for in Flutter, and how can you
use it to make a widget responsive?

MediaQuery provides information about the screen's size and other


display characteristics. You can use it to adjust a widget’s dimensions
or layout based on the screen size, such as setting a widget’s width to
a percentage of the screen width.

VIVA Questions
DART
62. What is Dart?

Dart is an object-oriented programming language developed by


Google, designed for building mobile, desktop, server, and web
applications.

63. What is a Future in Dart?

A Future represents a potential value or error that will be available at


some point in the future, commonly used in asynchronous
programming.

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

64. What does the async keyword do in Dart?

The async keyword is used to define a function as asynchronous,


allowing the use of await within the function to pause execution until a
Future completes.

65. How do you declare a list in Dart?

A list in Dart can be declared using List, for example: List<int>


numbers = [1, 2, 3];.

66. What is null safety in Dart?

Null safety in Dart ensures variables cannot contain null values unless
explicitly declared as nullable using a question mark (e.g., String?).

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

67. What are the key features of the Dart programming language?

Dart is an object-oriented, class-defined language that uses a C-style


syntax. It supports strong typing, asynchronous programming with
async and await, and a rich standard library. It's designed for front-
end development but can also be used for back-end and command- line
applications.

68. Explain the difference between var, final, and const in Dart.

var is used for variables whose type will be inferred at runtime. final is
used for variables that can only be set once but are initialized at
runtime. const is used for compile-time constants and variables
initialized at compile-time.

69. How does Dart handle asynchronous programming?

Dart handles asynchronous programming using Future, async, and await.


Future represents a potential value or error that will be available at
some point. async is used to declare a function as asynchronous, and
await pauses the function execution until the awaited Future
completes.

70. What are the different types of collections in Dart?

Dart provides several types of collections including List, Set, and


Map. List is an ordered collection of objects, Set is an unordered
collection of unique items, and Map is a collection of key-value pairs.

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

71. Explain the concept of null safety in Dart.

Null safety in Dart ensures that no variable can contain a null value unless
it is explicitly declared as nullable using a question mark (e.g., int?). This
helps to prevent null reference errors and improves code safety and
reliability.

72. What are the data types available in Dart?

Dart supports various data types including int, double, String, bool,
List, Map, Set, and more.

73. How do you define a class in Dart?

A class in Dart is defined using the class keyword, for example: class MyClass
{ /* class members */ }.

74. What is the difference between final and const in Dart?

final variables are initialized at runtime and can only be set once.
const variables are compile-time constants and are initialized
at compile-time.

75. What is a constructor in Dart?

A constructor is a special method of a class that is called when an


instance of the class is created. It is used to initialize the object's
properties.

76. How do you handle exceptions in Dart?

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

Exceptions in Dart are handled using try, catch, and finally blocks.
The try block contains code that may throw an exception, catch
handles the exception, and finally contains code that runs regardless of
whether an exception occurred.

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

77. What are Records?

Records are an anonymous, immutable, aggregate type. Like other


collection types, they let you bundle multiple objects into a single
object. Unlike other collection types, records are fixed-sized,
heterogeneous, and typed.

78. Write the record Syntax?

var record = ('first', a: 2, b: true, 'last');

79. How to create an empty String list in Dart?

var elements = <String>{};

80. How to use a generic method in Dart?

T first<T>(List<T> ts) {

// Do some initial work or error checking, then...

T tmp = ts[0]; // Do some additional processing... return

tmp;

81. List Built-in Types in Dart.


○ Numbers (int, double)
○ Strings (String)
○ Booleans (bool)
○ Records ((value1, value2))
○ Lists (List, also known as arrays)

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

○ Sets (Set)
○ Maps (Map)
○ Runes (Runes; often replaced by the characters API)
○ Symbols (Symbol)
○ The value null (Null)
82. How do you import the dart math library?

// Importing core libraries

import 'dart:math';

83. What is the purpose of the null-aware operator (??) in


Dart? The null-aware operator (??) returns the value on its left if it
is not null; otherwise, it returns the value on its right.
84. How does the null-aware assignment operator (??=) work
in Dart?
The null-aware assignment operator (??=) assigns a value to a variable
only if that variable is currently null.
85. What does the conditional member access operator (?.) do
in Dart?
The conditional member access operator (?.) allows you to call
methods or access properties on an object only if that object is not
null.
86. How is the cascade operator (..) used in Dart?
The cascade operator (..) allows you to make a sequence of operations
on the same object, returning the object itself at the end.

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

87. What is the purpose of the spread operator (...) in Dart?


The spread operator (...) is used to insert multiple values into a
collection.
88. How does the null-aware spread operator (...?) differ from
the spread operator in Dart?
The null-aware spread operator (...?) is used to insert multiple values
into a collection only if the provided collection is not null.

89. What is the function of the type test operator (is) in


Dart? The type test operator (is) checks if an object is of a
specific type, returning true or false.
90. What does the type cast operator (as) do in Dart?
The type cast operator (as) is used to cast an object to a specific type.

91. How can the ?. operator be useful in Dart when


dealing with potentially null values?
The ?. operator allows you to safely access properties or methods on
objects that might be null, preventing runtime errors.

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

92. What does the ! operator do in Dart when used after a


variable? The ! operator, when used after a variable, asserts that
the variable is not null, allowing you to access it as a non-null
value.

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

FLUTTER
1. What is Flutter and what are its main components?

Flutter is an open-source UI software development toolkit created by


Google. It is used to develop cross-platform applications from a single
codebase. The main components of Flutter are the Flutter framework,
the Flutter engine, and the Dart platform.

2. What is a widget in Flutter?

In Flutter, everything is a widget. Widgets are the building blocks of a


Flutter app's user interface. They describe what their view should look
like given their current configuration and state. Widgets can be
stateless or stateful, depending on whether they manage state.

3. Explain the difference between StatelessWidget and StatefulWidget.

StatelessWidget is immutable and cannot change once it is built. It does


not have any internal state that changes over time.
StatefulWidget, on the other hand, is mutable and can change during its
lifecycle. It has a State object that holds the widget's mutable state.

4. How does the Flutter rendering process work?

The Flutter rendering process involves three main stages: layout,


painting, and compositing. During the layout stage, Flutter determines
the size and position of each widget. In the painting stage, Flutter
draws the visual representation of each widget. In the compositing
stage, Flutter combines the painted layers to create the final output on
the screen.

5. What is the build method in Flutter?

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

The build method in Flutter is used to describe how to display the


widget in terms of other lower-level widgets. It is called whenever the
widget's configuration changes.

6. How do you navigate between screens in Flutter?

Navigation between screens in Flutter is managed using the


Navigator widget, with methods like push, pop, pushReplacement,
and popUntil.

7. What is a Container widget in Flutter?

A Container widget in Flutter is a versatile widget that can contain


other widgets and apply padding, margins, borders, and background
color.

8. What is setState in Flutter?

setState is a method used in a StatefulWidget to update the state of


the widget and trigger a rebuild of the UI.

9. What is a Stream in Flutter?

A Stream is a sequence of asynchronous events. It is used to handle


asynchronous data, such as data received from a network request or
user input over time.

10. How do you add external packages to a Flutter project?


External packages are added to a Flutter project by specifying

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

them in the dependencies section of the pubspec.yaml file and running


flutter pub get.
11. What is hot reload in Flutter?

Hot reload is a feature in Flutter that allows you to quickly see


changes in your code by preserving the app's state and injecting
updated code into the running app.

12. How do you handle user input in Flutter?

User input in Flutter is handled using widgets like TextField for text
input, and GestureDetector for handling gestures like taps and swipes.

13. What is the MaterialApp widget?

MaterialApp is a widget that wraps several widgets that are


commonly required for Material Design applications. It provides an
easy way to set up the basic structure of a Flutter app.

14. What is a Scaffold widget?

The Scaffold widget provides a framework for implementing the


basic visual layout structure of the Material Design layout, including
the app bar, drawer, and bottom navigation bar.

15. What is the purpose of the pubspec.yaml file in a


Flutter project?

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

The pubspec.yaml file is used to define the project's dependencies,


assets, and metadata. It specifies the packages and plugins that the
project depends on, as well as other configurations such as the
project's version and description. This file is essential for managing
and organizing the project's resources and dependencies.

16. What is MediaQuery used for in Flutter, and how can you
use it to make a widget responsive?

MediaQuery provides information about the screen's size and other


display characteristics. You can use it to adjust a widget’s dimensions
or layout based on the screen size, such as setting a widget’s width to
a percentage of the screen width.

17. What is the purpose of using LayoutBuilder in Flutter?

LayoutBuilder allows you to build widgets based on the constraints


passed down by their parent, enabling responsive designs that adapt
to different screen sizes or orientations.

18. How can Flexible and Expanded widgets help in


creating responsive layouts?

Flexible and Expanded widgets help by allowing child widgets to


adjust their sizes relative to available space, making it easier to create
layouts that adapt to different screen sizes.

19. What does the AspectRatio widget do in Flutter?

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

The AspectRatio widget ensures that a child widget maintains a


specific aspect ratio, helping to create responsive designs that preserve
proportions across different screen sizes.

20. How can MediaQuery be used to adjust font sizes in


a responsive design?

MediaQuery can be used to get the screen size and adjust font sizes
proportionally, ensuring that text remains readable across different device
sizes and orientations.

21. What is the difference between MediaQuery and


LayoutBuilder in handling responsive layouts?

MediaQuery provides information about the overall screen size,


while LayoutBuilder gives constraints specific to the widget’s parent,
allowing for more localized adjustments in responsive design.

22. How does the Row widget arrange its children,


and when would you use it?

The Row widget arranges its children horizontally in a line. It’s used
when you want to place widgets side by side, such as aligning buttons
or text elements horizontally.

23. What is the main difference between Row and Column


widgets in Flutter?

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

The Row widget arranges its children horizontally, while the Column
widget arranges its children vertically. Use Row for horizontal layouts
and Column for vertical layouts.

24. How can the Expanded widget be used within a Column to


make child widgets take up available space?

The Expanded widget allows a child widget in a Column to occupy


the remaining available space, ensuring that the widget sizes
dynamically adjust based on the space left by other widgets.

25. What does the Stack widget do, and when would you use it
in a layout?

The Stack widget overlays its children on top of each other, with
each child positioned relative to the stack's boundaries. It’s used when
you need to layer widgets, such as placing text over an image.

26. How can you control the positioning of children within a Stack?

You control positioning in a Stack using the Positioned widget,


which allows you to specify exact coordinates or relative offsets for
each child within the stack.

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

27. What is the purpose of the Align widget when used inside
a Stack?

The Align widget inside a Stack helps position a child widget


according to alignment properties, such as center, top-right,
or bottom-left, without using explicit positioning.

28. How do Row and Column widgets handle overflow


when their content exceeds available space?

By default, Row and Column widgets will overflow if their content


exceeds the available space. To handle overflow, you can use Flexible,
Expanded, or SingleChildScrollView to manage or scroll the content.

29. How does the Navigator widget manage navigation


between screens in Flutter?
The Navigator widget manages navigation by maintaining a stack of
Route objects. You can push a new route onto the stack to navigate
to a new screen and pop a route off the stack to return to a previous
screen.

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

30. What is the difference between named routes


and unnamed (anonymous) routes in Flutter?
Named routes are registered with the Navigator using a unique
string identifier and are accessed by name, making navigation more
manageable and readable. Unnamed routes are created directly within
the code without a specific name and are generally used for simple
navigation scenarios.

31. How do you define and use a named route in


a Flutter application?
You define a named route by adding it to the routes table in the
MaterialApp or CupertinoApp widget. You can then navigate
to this route using Navigator.pushNamed(context,
'routeName').

32. How can you pass data between routes using unnamed routes?
Data can be passed between unnamed routes by using the
Navigator.push method and providing arguments to the route’s
constructor. For example,
Navigator.push(context,
MaterialPageRoute(builder: (context) =>
SecondPage(data: 'someData'))), where SecondPage can receive the
data through its constructor.

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

33. What is the role of the RouteSettings class in


Flutter's navigation system?
The RouteSettings class holds information about the route,
including its name and arguments. This information can be accessed
within the route’s widget to manage navigation and pass data between
screens.

34. What is the purpose of the setState method in Flutter?


The setState method is used to notify the framework that the
internal state of a widget has changed, causing the widget to rebuild
with the new state.

35. How does the setState method impact the widget tree?
Calling setState triggers a rebuild of the widget tree, updating the UI to
reflect the new state.

36. What is the Provider package used for in Flutter?


The Provider package is used for state management by allowing data
to be shared and accessed across different parts of the widget tree without
the need for manual prop drilling.

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

37. How do you define a ChangeNotifier in Flutter using the


Provider package?

class MyModel extends ChangeNotifier { int

_count = 0;

int get count => _count; void

increment() {

_count++; notifyListeners();

38. How do you provide a ChangeNotifier to the widget tree


using Provider?

void main() {

runApp(

ChangeNotifierProvider(

create: (context) => MyModel(),

child: MyApp(),

),

);

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

39. How do you access the provided data in a widget


using Provider?

@override

Widget build(BuildContext context) {

final model = Provider.of<MyModel>(context);

return Text('Count: ${model.count}');

40. What is the difference between setState and Provider


in state management?
setState is used for managing local state within a single widget,
whereas Provider is used for managing global state that needs to be
accessed across multiple widgets in the widget tree.

41. Can you use setState and Provider together in a


Flutter application?
Yes, setState can be used for local state management within a

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

widget, while Provider can be used for global state management across
the widget tree.

42. What is a custom widget in Flutter?


A custom widget is a reusable UI component that encapsulates
specific functionality and appearance, allowing for modular and
maintainable code.

43. How do you create a basic custom widget in Flutter?

class CustomButton extends StatelessWidget { final

String label;

final VoidCallback onPressed;

CustomButton({required this.label, required this.onPressed});

@override

Widget build(BuildContext context) {

return ElevatedButton(

onPressed: onPressed, child:

Text(label),

);

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

44. Why would you create custom widgets in a Flutter


application? Creating custom widgets promotes code reuse, improves
readability, and allows for consistent styling and behavior across
different parts of the application.

45. How can you pass data to a custom widget in Flutter?


Data can be passed to a custom widget through its constructor.
For example:

CustomButton(label: 'Click Me', onPressed: () => print('Button pressed'));

46. How do you handle user interactions in a custom widget?


User interactions can be handled by defining callback functions in
the custom widget and passing them down from the parent widget.
For example:

class CustomButton extends StatelessWidget { final

String label;

final VoidCallback onPressed;

CustomButton({required this.label, required this.onPressed}); @override

Widget build(BuildContext context) {

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

return ElevatedButton(

onPressed: onPressed,

child: Text(label),

);

47. Can you create custom widgets with state in Flutter? If


so, how?
Yes, you can create custom widgets with state by extending
StatefulWidget and implementing the associated State class. For
example:
class CustomCounter extends StatefulWidget { @override

_CustomCounterState createState() => _CustomCounterState();

class _CustomCounterState extends State<CustomCounter> { int

_count = 0;

void _increment() {

setState(() {

_count++;

});

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

@override

Widget build(BuildContext context) {

return Column(

children: [

Text('Count: $_count'),

ElevatedButton(

onPressed: _increment, child:

Text('Increment'),

),

],

);

48. What are the benefits of using custom widgets for


specific UI elements?
The benefits include code reuse, improved readability, easier
maintenance, consistent styling, and the ability to isolate and test
individual components independently.
49. What are the advantages of using custom widgets in
Flutter for building complex UIs?
Custom widgets allow for modular and reusable code, making it easier
to manage and maintain large codebases. They help in maintaining a
consistent look and feel across the application and promote

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

separation of concerns by isolating specific functionality into self-


contained components.

50. How does the StatefulWidget differ from the


StatelessWidget in Flutter, and when should each be
used?
StatefulWidget is used when a widget needs to maintain mutable
state that can change over time, requiring the widget to rebuild in
response to state changes. StatelessWidget, on the other hand, is used
for widgets that do not require any internal state and remain static
throughout their lifecycle. Use StatefulWidget for dynamic
components like forms, counters, or animations, and StatelessWidget
for static content like text labels, icons, or layout elements.

51. What is the purpose of the AnimationController class in


Flutter?
The AnimationController class is used to control the animation,
including starting, stopping, and reversing the animation. It also
provides access to the animation's current value and state.

52. How do you create an AnimationController in Flutter?

AnimationController _controller = AnimationController(

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

duration: const Duration(seconds: 2), vsync:

this,

);

53. What is the TickerProvider and why is it needed


for animations in Flutter?
The TickerProvider is required to create an
AnimationController. It provides a Ticker that signals when a
frame should be displayed, allowing Flutter to synchronize animations
with the device's refresh rate.

54. What is the CurvedAnimation class used in Flutter?

The CurvedAnimation class is used to apply a non-linear curve to an


animation, making it more natural and fluid.

55. What is the difference between Tween and


TweenAnimationBuilder in Flutter?
Tween defines a range of values that an animation can interpolate
between. TweenAnimationBuilder simplifies the process by

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

managing the animation and rebuilding the widget when the animation
value changes.

56. How can you repeat an animation infinitely in Flutter?


By setting the AnimationController to repeat:

_controller.repeat();

57. What are Staggered Animations in Flutter and how are


they implemented?
Staggered animations involve multiple animations that start at
different times but are coordinated to create a unified effect. They can be
implemented using Interval objects to define the start and end times of
each animation segment.

58. What is the role of the Transform widget in


Flutter animations?

The Transform widget is used to apply a transformation (such as


scaling, rotating, or translating) to its child widget, which is commonly
used in animations to move or change the appearance of the widget.

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

59. What is the purpose of unit testing in Flutter applications?


To test individual units of code, such as functions or classes, to
ensure they work as expected.

60. How does widget testing differ from unit testing in


Flutter? Widget testing verifies the behavior and appearance
of individual widgets, while unit testing tests logic in isolation.
61. What function is used to write widget tests in Flutter?
The testWidgets function is used to write widget tests in Flutter.

62. What package provides tools and utilities for writing


tests in Flutter?
The flutter_test package provides tools and utilities for writing tests
in Flutter.

63. What is integration testing in Flutter?


Integration testing verifies that different parts of the application work
together as expected.

64. How do you run tests in a Flutter application?


Tests can be run using the flutter test command in the terminal.

Downloaded by Md Ateeq (mdateeq807@gmail.com)


lOMoARcPSD|58593188

65. How can you verify the state of a widget after


a user interaction in a Flutter test?
By using the expect function with matchers to check the widget's
properties or by querying the widget tree.
66. Why is it important to test error states and edge cases in
Flutter applications?
To ensure the application handles unexpected situations gracefully and
provides a reliable user experience.

67. What is a common challenge in Flutter testing and how


can it be addressed?
A common challenge is flaky tests, which can be addressed by writing
stable and deterministic tests.

Downloaded by Md Ateeq (mdateeq807@gmail.com)

You might also like