Flutter Questions
Flutter Questions
Answers PDF
1. What is Flutter?
Flutter is a framework for developing apps. It is an is open source framework developed by
Google. It enables developers to create apps that are natively compiled for mobile, web, and
desktop platforms, all from a single codebase.
Flutter also comes with a rich set of customizable pre-built widgets that can be used to
create beautiful and responsive user interfaces. Developers can also create their own
custom widgets to meet their specific needs.
This saves time and resources that would otherwise be spent on developing separate
codebases for each platform.
Appealing UI
Flutter offers a rich set of customizable widgets that allow developers to create beautiful and
engaging user interfaces. It also provides a range of animations and effects that can help
make an app feel more responsive and interactive.
High-performance
Flutter apps are built using Dart, which compiles to native code for high performance on
each platform. This results in faster app startup times, smoother animations, and better
overall performance.
Easy to learn
Flutter's simplicity and ease of use make it accessible to both experienced and new
developers. It has clear and concise documentation, along with a large community of
developers who contribute to its development and support each other. One can easily learn it
with a Flutter course.
Hot Reload
This feature allows developers to instantly see the effects of changes made to the code
without having to rebuild the entire app. This reduces development time and makes it easier
to iterate on the design and functionality of an app.
Cross-platform development
Flutter allows developers to write code once and deploy it across multiple platforms such as
iOS, Android, web, and desktop. This can save time and resources that would otherwise be
spent on developing separate codebases for each platform.
It has become increasingly popular in recent years, as it allows developers to reach a larger
audience while minimizing development time and cost.
5. Which programming language is used by Flutter?
Flutter uses the Dart programming language, which was created by Google.
It is a compiled language, which means that it is translated into machine code at runtime.
This allows for high-performance execution of Dart code, making it well-suited for mobile app
development.
When an app is built using Flutter, the Flutter framework compiles the Dart code into native
code for the target platform. This native code then communicates with Skia to render
graphics on the screen.
Skia uses a retained mode graphics API, which means that it maintains a persistent object
representation of the graphics being rendered. This allows for more efficient rendering, as
objects can be reused and modified without having to be recreated from scratch each time.
Moreover, Skia also provides a range of features, such as anti-aliasing, text rendering, and
image processing, which can help create high-quality and visually appealing graphics.
In Flutter, everything is a widget, including the app itself, the app's layout, and the individual
elements that make up the layout.
● Stateless widgets are immutable, meaning they do not change over time. These
widgets are used to create elements that do not change, such as text labels or icons.
● Stateful widgets, on the other hand, can change over time. These widgets are used
to create elements that respond to user interaction or other events, such as buttons
or text fields.
Smaller community
Compared to other popular frameworks like React Native and Xamarin, the Flutter
community is relatively small. This means that finding support and resources can be more
challenging, and finding developers with experience in the framework may be harder.
Learning curve
While Dart, the language used by Flutter, is easy to learn, developers unfamiliar with reactive
programming or the widget-based architecture of Flutter may face a steep learning curve
when getting started with the framework.
Refreshes the app's state and UI Completely restarts the app's Dart
Definition in real-time while preserving the Virtual Machine (VM), which destroys
app's current state. the app's current state and UI.
Retains
Yes No
State
To see changes made in code in To reset the app to its initial state or to
Use Case real-time without losing the clear its current state after making
current state of the app. major changes to the code.
All platforms where Flutter runs, All platforms where Flutter runs,
Supported
including iOS, Android, Web, and including iOS, Android, Web, and
on
Desktop. Desktop.
It's used by the Flutter package manager, called "pub", to manage the dependencies of your
app and download them from the internet.
● name: The name of your app or package, which should be unique and easy to
remember.
● description: A short description of your app or package.
● version: The current version of your app or package.
● dependencies: A list of packages that your app or package depends on, along with
their versions.
● dev_dependencies: A list of packages that your app or package depends on only for
development purposes, such as testing or documentation.
● flutter: A section that contains settings specific to Flutter, such as the SDK version
and the assets used in the app.
name: my_app
description: A sample Flutter app
version: 1.0.0
dependencies:
http: ^0.13.4
flutter_bloc: ^7.4.1
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
assets:
- assets/images/
By including this file in your Flutter project, you can easily manage and track your app's
dependencies and assets, making it easier to develop and maintain your app over time. Be
prepared for such concepts, because it is one of the top Flutter interview questions.
This widget provides several important features to your Flutter app, including:
● A default theme that provides a consistent look and feel for all widgets in your app.
● Navigation and routing management, which makes it easy to move between different
screens or pages in your app.
● Localization support, which allows you to translate your app into different languages.
● Support for displaying dialogs and snackbars, which are common UI components in
many apps.
● A built-in app bar that displays the app's title and can contain buttons for navigating
to other screens or performing actions.
● A drawer widget that can be used to provide navigation to other parts of the app.
● A floating action button (FAB) that is often used for triggering important actions or for
adding new content.
● A bottom navigation bar for switching between different sections of the app.
The Scaffold widget is a convenient way to quickly build the basic structure of your app, and
it can be customized to fit your specific needs.
For example, you can customize the app bar with a custom logo, add additional buttons to
the FAB, or customize the appearance of the bottom navigation bar.
In addition, this widget can be combined with other widgets to create more complex layouts,
such as tabbed interfaces or scrolling lists. It is one of the most asked Flutter interview
questions for answers.
● You create a Future object that represents the asynchronous computation that will
eventually provide the data you need.
● You pass this Future to the FutureBuilder widget, which will wait for the future to
complete and then rebuild the UI with the data that is returned.
● While the future is still being processed, FutureBuilder can display a loading indicator
or placeholder widget.
Example
Here's an example of how to use FutureBuilder:
FutureBuilder(
future: getData(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data);
} else if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
return CircularProgressIndicator();
}
},
);
Here, getData() is a function that returns a Future that eventually provides a string value.
The builder function takes two arguments: the current BuildContext and a snapshot object
that contains the current state of the Future.
If the snapshot has data, it displays the data using a Text widget. If there is an error, it
displays an error message. Otherwise, it displays a CircularProgressIndicator widget to
indicate that the data is still being loaded.
This topic is important to prepare for both beginners and experienced. For instance, if you
are looking for Flutter interview questions for 1 year experience, then it is a relevant topic to
prepare for.
Streams can be used to handle asynchronous data by providing a way to receive new data
as soon as it becomes available. Streams work by sending a sequence of events to a
listener, which can then react to each event as it arrives.
In Flutter, the Stream class represents a stream of data, and the StreamBuilder widget can
be used to listen to and process the data in the stream.
Here, countStream() is a function that returns a Stream<int> that increments a counter every
second. The StreamBuilder listens to this stream and updates the UI with the latest value of
the counter. If there is no data yet, it displays a CircularProgressIndicator widget.
The purpose of the ListView widget is to provide a way to display a large amount of data in a
limited amount of space. It allows users to scroll through the data and see more content than
would be possible with a fixed-size container. The ListView widget can be used to display a
variety of data types, such as text, images, icons, and custom widgets.
In addition to providing scrolling functionality, the ListView widget also provides several
features to improve the user experience, such as:
● Lazy loading: the ability to load and display only the data that is currently visible on
the screen, which can improve performance and reduce memory usage.
● Infinite scrolling: the ability to load more data as the user scrolls down the list,
which can provide a seamless and uninterrupted browsing experience.
● Separators: the ability to display separators between list items to improve readability
and distinguish between different items.
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('ListView Example'),
),
body: ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(items[index]),
);
},
),
),
);
}
}
Here, we define a list of items and use the ListView.builder constructor to display them in a
scrolling list. The itemCount property specifies the number of items in the list, and the
itemBuilder function is called for each item to build a ListTile widget that displays the item's
text.
Both mainAxisAlignment and crossAxisAlignment are properties of widgets that are used to
align child widgets within their parent widget. The main axis is defined as the primary axis of
the parent widget, while the cross axis is defined as the axis perpendicular to the main axis.
Here's a comparison table to highlight the differences between mainAxisAlignment and
crossAxisAlignment:
InkWell:
● A Material design widget that provides a visual splash effect when the user taps on it.
● Best used on Material design surfaces, when the user needs to visually confirm their
touch input.
● Provides a visual ink splash effect when tapped, which can be customized with the
splashColor, highlightColor, and radius properties.
● Requires a Material design parent widget, such as Material, Scaffold, or Card, in
order to work correctly.
GestureDetector:
● A general-purpose widget that can detect various user gestures, such as taps, drags,
and long presses.
● Best used for custom gestures or non-material design interfaces.
● Provides no visual feedback by default, but can be customized with the feedback
property.
● Does not require a Material design parent widget, and can be used on any type of
widget.
Requires
Gesture Material
Widget Description Use case feedback design
Best used on
A Material design
Material design Provides a
widget that provides
surfaces, when the visual ink
InkWell a visual splash effect Yes
user needs to splash effect
when the user taps
visually confirm when tapped.
on it.
their touch input.
A general-purpose
widget that can Best used for Provides no
GestureDete detect various user custom gestures or visual
No
ctor gestures, such as non-material feedback by
taps, drags, and long design interfaces. default.
presses.
With our comprehensive guide, you can ensure that you are well-prepared to tackle any
question that comes your way during your interview.
Familiar syntax
Dart has a familiar syntax that is similar to other popular programming languages like Java
and JavaScript, making it easier for developers to learn and write code in Dart.
Strong typing
Dart is a strongly typed language, which means that variables and function return types must
be explicitly defined. This helps prevent bugs and makes code easier to read and
understand.
Single codebase
With Dart and Flutter, developers can build native apps for both iOS and Android platforms
using a single codebase. This can help reduce development time and costs, while also
making it easier to maintain and update the app over time.
Open source
Dart is an open-source programming language. It is freely available and can be modified and
improved by developers around the world. This helps ensure that the language and
associated tools remain up-to-date and relevant.
Learn DART for Flutter | What is Dart Programming? | Dart Programming Language
Packages
These are collections of Dart code that provide reusable functionality, such as widgets, APIs,
and other utility classes.
These can be created by anyone and shared through the Dart package repository, Pub. To
use a package in your app, you simply need to add a dependency to it in your pubspec.yaml
file and run flutter pub get to download and install it.
Plugins
On the other hand, plugins are similar to packages but provide native code functionality for
specific platforms such as iOS and Android. These allow you to access native platform APIs,
such as camera, geolocation, and Bluetooth, from your Flutter app.
Plugins are created by the Flutter community and can be found in the Flutter plugins
repository. To use a plugin in your app, you need to add a dependency to it in your
pubspec.yaml file and import it in your Dart code.
It is one of the most important Flutter developer interview questions in 2023. So prepare well
for it.
Debug mode
This is the default mode used during development. In debug mode, the app is compiled with
additional debugging information, and hot-reload and hot-restart are available.
This mode is slower than release mode, but it provides better error messages and makes it
easier to diagnose and fix issues during development.
Profile mode
In profile mode, the app is optimized for performance, with extra diagnostic information and
profiling enabled. This mode is faster than debug mode, but it still allows developers to track
down issues that may not be evident in release mode.
Release mode
This is the final mode used for production releases. In release mode, the app is compiled
with maximum optimization and without debugging information.
This mode produces the fastest and smallest possible code, which is ideal for distributing the
app to end users. However, it also means that debugging tools like hot-reload are not
available, and errors may be harder to diagnose.
Android Studio
It is the official IDE for Android development, and it has excellent support for Flutter. Android
Studio includes features like code completion, debugging, and hot-reload. It is also
integrated with the Flutter SDK and offers tools for building, testing, and deploying apps.
IntelliJ IDEA
It is a popular Java IDE that also offers excellent support for Flutter development. IntelliJ
IDEA provides features like code completion, debugging, and hot-reload. It is also
customizable and supports many programming languages.
Emacs
It is a powerful and customizable text editor that supports Flutter development. Emacs offers
features like syntax highlighting, code completion, and debugging, and it can be extended
with many plugins.
Sublime Text
Sublime Text is a lightweight and customizable text editor that supports Flutter development.
It includes features like syntax highlighting, code completion, and debugging, and it can be
customized with many plugins.
While preparing for Flutter interview questions, you must have a clear idea of the top editors
and how to use them.
22. Which are the most popular apps that use Flutter?
Flutter has gained popularity among developers due to its ease of use, cross-platform
capabilities, and rich set of features.
Here are some popular apps that have been built using Flutter:
Google Ads
Google Ads is a mobile app for managing Google Ads campaigns. It was built using Flutter
and offers a smooth and responsive user experience.
Alibaba
Alibaba, the popular e-commerce platform, used Flutter to develop its Xianyu app, which
offers a secondhand marketplace for users in China.
Reflectly
Reflectly is a mindfulness app that uses Flutter for its mobile interface. It offers a clean and
user-friendly design, with features like journaling and personalized mindfulness exercises.
Realtor.com
Realtor.com, a popular real estate platform, used Flutter to build its mobile app. It offers
features like property search, filtering, and alerts.
Hamilton
Hamilton is a popular Broadway musical that offers a mobile app built with Flutter. It provides
information about the show, behind-the-scenes content, and ticket purchasing.
Hookle
Hookle is a social media management app that uses Flutter for its mobile interface. It offers
features like post scheduling, analytics, and cross-platform publishing.
Coach Yourself
Coach Yourself is a mental wellness app that uses Flutter for its mobile interface. It offers
features like mood tracking, stress management, and personalized coaching.
At its core, a Provider is a simple object that holds a piece of data. The data can be anything
from a simple boolean value to a complex object. When a widget needs access to the data, it
can use the Provider to retrieve it.
The Provider design pattern is based on the concept of dependency injection, which is a way
of providing objects with the dependencies they need to function. In the context of Flutter, a
Provider is used to provide widgets with the data they need to render themselves.
Flutter provides a built-in Provider package that makes it easy to use the Provider pattern in
your application. The package provides several classes and utilities that make it easy to
manage and update your app's state.
Easier to maintain
A Provider can make your code easier to maintain by reducing the amount of boilerplate
code that you need to write.
Optimize images
Optimize your images by compressing them and reducing their size. You can also use the
CachedNetworkImage package to cache network images and reduce the amount of data
that is transferred over the network.
Such topics are commonly asked when you apply for a job. Hence, be prepared for this type
of Flutter interview questions for 2 years experience. It’s also relevant for senior developers
as well.
setState() Provider
Type of state
Local state management Global state management
management
Tightly coupled - state and Loosely coupled - state and UI logic are
Coupling UI logic are intertwined in separated, making the code easier to
the same widget maintain
SharedPreferences:
This is a key-value store that can be used to store small amounts of data such as user
preferences. SharedPreferences can be accessed across different screens and can be
useful for storing simple data.
SQLite:
SQLite is a relational database management system that can be used to store and retrieve
complex data in a Flutter application. It is a popular choice for persisting data in mobile
applications because it is lightweight and provides a fast and reliable way to store data.
Files:
Files can be used to store data in a structured format such as JSON or CSV. This is useful
when you need to store larger amounts of data or when you need to create custom file
formats.
Cloud storage:
You can use cloud storage services such as Firebase Cloud Firestore or Google Cloud
Storage to store and retrieve data in a Flutter application. This is useful when you need to
share data between multiple users or devices.
Hive:
Hive is a lightweight and fast NoSQL database that can be used to persist data in a Flutter
application. It is optimized for mobile devices and provides a simple and easy-to-use API for
storing and retrieving data.
ObjectBox:
ObjectBox is a high-performance NoSQL database that can be used to persist data in a
Flutter application. It is optimized for mobile devices and provides a simple and easy-to-use
API for storing and retrieving data.
The choice of the persistence mechanism depends on the specific requirements of your
application. For simple data, SharedPreferences or files may be sufficient, while more
complex data may require the use of a relational or NoSQL database.
While preparing for Flutter developer interview questions and answers, make sure to know
answer to these concepts.
This widget is typically used to ensure that the content of an app is not hidden by these
system UI elements. For example, on devices with a notch or a camera cutout, the SafeArea
widget can be used to ensure that the content of the app is not hidden behind the notch.
To use the SafeArea widget, you simply wrap your content widget inside it. The SafeArea
widget will then ensure that the content is inset by the safe area of the device.
Example:
Here is an example of how to use the SafeArea widget in Flutter:
import 'package:flutter/material.dart';
In this example, the SafeArea widget is used to wrap the Scaffold widget, ensuring that the
content of the app is inset by the safe area of the device.
Text input:
To handle text input from the user, you can use the TextFormField or TextField widgets.
These widgets provide a text input field that the user can type into. To handle the input, you
can use the onChanged or onSubmitted callback to get the text entered by the user and
update your app's state accordingly.
Button press:
To handle button press events, you can use the RaisedButton, FlatButton, or IconButton
widgets.
These widgets provide a button that the user can tap to trigger an action in your app. To
handle the button press event, you can use the onPressed callback to execute the desired
action.
Gesture detection:
To handle gestures such as taps, swipes, or pinches, you can use the GestureDetector
widget.
This widget allows you to detect a wide range of gestures and trigger an action in response.
To handle the gesture, you can use the onTap, onDoubleTap, onLongPress, or other callback
functions provided by the GestureDetector widget.
Slider or switch:
To handle input from sliders or switches, you can use the Slider or Switch widgets.
These widgets provide a slider or switch that the user can use to select a value or toggle a
setting. To handle the input, you can use the onChanged callback to update your app's state
with the new value or setting.
Dropdown list:
To handle input from a dropdown list, you can use the DropdownButton widget.
This widget provides a dropdown list that the user can select an item from. To handle the
selection, you can use the onChanged callback to update your app's state with the selected
item.
AnimationController:
You can use the AnimationController class to control the duration, direction, and intensity of
the animation. You can define the animation values and specify the duration, and the
AnimationController will update the values over time.
Tween:
You can use the Tween class to define the range of values that the animation will interpolate
between. The Tween class takes a begin and an end value and returns a value between the
two values based on the animation's progress.
AnimatedWidget:
You can use the AnimatedWidget class to create a widget that automatically rebuilds itself
when the animation updates. This allows you to create complex animations without having to
manually update the widget's state.
AnimatedBuilder:
You can use the AnimatedBuilder class to build a widget tree that animates when the
animation updates. This allows you to build complex animations with multiple widgets and
customize the animation's behavior.
Hero animations:
You can use Hero animations to create a smooth transition between two screens. You can
use the Hero widget to wrap the widget that you want to transition and specify a unique tag.
When the widget is clicked, it will smoothly transition to the same widget on the new screen.
Implicit animations:
You can use Implicit animations to create simple animations that are triggered by a change
in the widget's properties. You can use the AnimatedOpacity, AnimatedPadding, and
AnimatedContainer classes to animate changes in opacity, padding, and size, respectively.
When you have some experience, you must expect such Flutter interview questions for 3
years experience.
Here is a comparison table that explains the differences between the two:
main() runApp()
Required Optional
The main() function is the entry point of a Flutter app and is required in every Flutter app. It
sets up the Flutter framework and initializes the app. It can also take command line
arguments and be used to initialize external dependencies. The main() function must return
void.
The runApp() function, on the other hand, is optional and is used to start the app's widget
tree. It takes a widget as an argument, which becomes the root of the widget tree.
The widget tree is the hierarchical structure of widgets that make up the app's user interface.
The runApp() function also initializes the app's default route and sets up the app's top-level
widget tree. The runApp() function returns void.
Program:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('My List'),
),
body: ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
final item = items[index];
return ListTile(
title: Text(item['title']),
subtitle: Text(item['subtitle']),
onTap: () {
// do something when the item is tapped
},
);
},
),
);
}
}
Explanation:
Here, we define a MyListWidget class that extends StatefulWidget. The widget's state
includes a List<dynamic> variable called items, which will store the items fetched from the
API endpoint.
When the widget is created, the initState method is called, which in turn calls _fetchItems.
This method sends an HTTP GET request to the API endpoint using the http package and
updates the widget's state with the fetched items.
The widget's build method returns a Scaffold with an AppBar and a ListView.builder. The
ListView.builder is used to display the items in a scrollable list. The itemCount property is set
to the length of the items list, and the itemBuilder function is called for each item in the list.
The ListTile widget is used to display each item's title and subtitle. You can customize this
widget according to your needs.
Finally, you can add any functionality you like when the user taps an item by defining it in the
onTap property of the ListTile.
34. Write a Flutter widget that displays a form for a user to input
data and sends it to an API endpoint.
Program:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
Explanation:
Here, we define a MyFormWidget class that extends StatefulWidget. The widget's state
includes a GlobalKey<FormState> called _formKey, which is used to identify the form and
validate its inputs. The state also includes two String variables called _name and _email,
which will store the user's input.
The build method returns a Scaffold with an AppBar and a Form. The Form widget contains
two TextFormFields, one for the user's name and one for their email. Both of these fields
have validation logic and save the user's input when the form is submitted.
Lastly, there is an ElevatedButton that triggers the _submitForm method when pressed. This
method sends an HTTP POST request to the API endpoint using the http package and
includes the user's name and email in the request body. If the request is successful, you can
handle the success case according to your needs. Otherwise, an exception is thrown.
Program:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter Counter App'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Counter:',
style: TextStyle(fontSize: 24),
),
Text(
'$_counter',
style: TextStyle(fontSize: 48),
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
Explanation:
In this implementation, the CounterPage widget is a stateful widget that holds the current
count in the _counter variable.
The _incrementCounter method is called when the floating action button is pressed, and it
uses the setState method to update the _counter variable and trigger a rebuild of the widget
tree.
The current count is displayed using two Text widgets, and the floating action button is used
to trigger the _incrementCounter method.
36. Write a Flutter widget that displays an image from a URL and
allows the user to zoom in and out.
Program:
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:cached_network_image/cached_network_image.dart';
ZoomableImage({required this.imageUrl});
@override
_ZoomableImageState createState() => _ZoomableImageState();
}
@override
Widget build(BuildContext context) {
return InteractiveViewer(
minScale: _minScale,
maxScale: _maxScale,
child: CachedNetworkImage(
imageUrl: widget.imageUrl,
fit: BoxFit.contain,
placeholder: (context, url) => CircularProgressIndicator(),
errorWidget: (context, url, error) => Icon(Icons.error),
),
);
}
}
Explanation:
In this implementation, the ZoomableImage widget takes a String parameter imageUrl that
represents the URL of the image to be displayed. The InteractiveViewer widget is used to
enable zooming functionality, and the minScale and maxScale properties are used to set the
minimum and maximum scale values that the user can zoom to.
The CachedNetworkImage widget is used to load the image from the URL, and the fit
property is set to BoxFit.contain to ensure that the entire image is visible even when zoomed
in. A CircularProgressIndicator is displayed while the image is loading, and an Icon with the
error icon is displayed if the image fails to load.
37. Implement a Flutter widget that displays a map and allows the
user to add markers to it.
Here's an example implementation of a Flutter code that displays a map using the Google
Maps Flutter plugin and allows the user to add markers to it:
Program:
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Map with Markers'),
),
body: GoogleMap(
onMapCreated: _onMapCreated,
initialCameraPosition: CameraPosition(
target: LatLng(37.7749, -122.4194),
zoom: 12,
),
markers: markers,
onTap: _onAddMarker,
),
);
}
}
Explanation:
Here, the MapWithMarkers widget is a stateful widget that holds a set of markers in the
markers variable. The GoogleMap widget is used to display the map, and the onMapCreated
property is used to get a reference to the GoogleMapController.
The initialCameraPosition property is used to set the initial camera position, and the markers
property is used to display the set of markers on the map.
The _onAddMarker method is called when the user taps on the map, and it adds a new
marker to the set of markers at the location of the tap. The setState method is called to
trigger a rebuild of the widget tree and update the markers on the map.
In this example, the Google Maps Flutter plugin is used to display the map and handle the
marker creation. Note that you will need to follow the plugin's setup instructions to enable
Google Maps on your app.
38. Write a Flutter widget that displays a scrollable list of items with
pagination.
Below is the code to display a scrollable list of items with pagination in Flutter:
Program:
import 'package:flutter/material.dart';
void _loadMoreItems() {
if (!_isLoading) {
setState(() {
_isLoading = true;
});
@override
void initState() {
super.initState();
_scrollController.addListener(() {
if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent) {
_loadMoreItems();
}
});
}
@override
void dispose() {
_scrollController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Paginated List'),
),
body: ListView.builder(
controller: _scrollController,
itemCount: _items.length + (_isLoading ? 1 : 0),
itemBuilder: (context, index) {
if (index == _items.length) {
return Center(
child: CircularProgressIndicator(),
);
} else {
return ListTile(
title: Text(_items[index]),
);
}
},
),
);
}
}
Explanation:
In this implementation, the PaginatedList widget is a stateful widget that holds a list of items
in the _items variable, a scroll controller in the _scrollController variable, the current page
number in the _currentPage variable, and a loading flag in the _isLoading variable.
The _loadMoreItems method is called when the user scrolls to the end of the list, and it
simulates loading more items by adding 20 more items to the _items list and incrementing
the _currentPage variable. The _isLoading flag is used to show a CircularProgressIndicator
at the end of the list while the next page of items is being loaded.
In the initState method, the _scrollController is set up to listen for changes in the scroll
position, and when the user reaches the end of the list, the _loadMoreItems method is
called.
In the build method, a ListView.builder widget is used to display the list of items. The
itemCount is set to the length of the _items list plus one if _isLoading is true, to include the
CircularProgressIndicator at the end of the list.
The itemBuilder method returns a ListTile for each item in the _items list, and the
CircularProgressIndicator if _isLoading is true and the index is equal to the length of the
_items list.
Program:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:charts_flutter/flutter.dart' as charts;
@override
void initState() {
super.initState();
fetchData().then((data) => setState(() => _buildChart(data)));
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Chart with API'),
),
body: _chartData.isNotEmpty
? charts.BarChart(
_chartData,
animate: true,
vertical: false,
barRendererDecorator: charts.BarLabelDecorator<String>(),
)
: Center(
child: CircularProgressIndicator(),
),
);
}
}
class ChartData {
final String label;
final int value;
Explanation:
Here, the ChartWithAPI widget is a stateful widget that holds the chart data in the _chartData
variable. The _buildChart method is called to create the chart data series from a list of
ChartData objects. The fetchData method is used to fetch the chart data from an API
endpoint and return a list of ChartData objects.
● In the initState method, the fetchData method is called to fetch the chart data and
build the chart when the widget is first created.
● In the build method, a BarChart widget from the charts_flutter package is used to
display the chart data. If the chart data is not empty, the chart is displayed with
animated bars and a horizontal orientation. If the chart data is empty, a
CircularProgressIndicator is shown in the center of the screen while the data is being
fetched.
● The ChartData class is a simple data class that holds a label and a value for each
data point in the chart. It also includes a fromJson factory method to parse the JSON
data returned by the API endpoint into ChartData objects.
40. Write a Flutter widget that displays a timer that counts down
from a given time.
here's an example implementation of a Flutter widget that displays a timer that counts down
from a given time:
Program:
import 'dart:async';
import 'package:flutter/material.dart';
CountdownTimer({required this.initialSeconds});
@override
_CountdownTimerState createState() => _CountdownTimerState();
}
@override
void initState() {
super.initState();
_secondsLeft = widget.initialSeconds;
_timer = Timer.periodic(Duration(seconds: 1), (_) => _updateTimer());
}
@override
void dispose() {
_timer.cancel();
super.dispose();
}
void _updateTimer() {
setState(() {
if (_secondsLeft > 0) {
_secondsLeft--;
} else {
_timer.cancel();
}
});
}
@override
Widget build(BuildContext context) {
int minutes = _secondsLeft ~/ 60;
int seconds = _secondsLeft % 60;
return Text(
'${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}',
style: TextStyle(fontSize: 48.0),
);
}
}
Explanation:
In this implementation, the CountdownTimer widget is a stateful widget that holds the
number of seconds left in the _secondsLeft variable and the Timer object in the _timer
variable.
● In the initState method, the _secondsLeft variable is initialized to the value of
widget.initialSeconds and the _timer object is initialized to a Timer.periodic object that
updates the timer every second.
● In the dispose method, the _timer object is cancelled to prevent memory leaks.
● In the build method, the number of minutes and seconds left are calculated from the
_secondsLeft variable and displayed in a Text widget with a font size of 48.0. The
padLeft method is used to add a leading zero to the minutes and seconds strings if
they are less than 10.
41. Implement a Flutter widget that allows the user to drag and drop
items to reorder them.
Program:
import 'package:flutter/material.dart';
ReorderableList({required this.items});
@override
_ReorderableListState createState() => _ReorderableListState();
}
@override
void initState() {
super.initState();
_items.addAll(widget.items);
}
@override
Widget build(BuildContext context) {
return ReorderableListView(
onReorder: _onReorder,
children: _items
.map((item) => ListTile(
key: ValueKey(item),
title: Text(item),
leading: Icon(Icons.drag_handle),
))
.toList(),
);
}
}
Explanation:
Here, the ReorderableList widget is a stateful widget that holds the list of items in the _items
variable.
● In the _onReorder method, the _items list is updated when an item is dragged and
dropped to a new position. The old item is removed from its old index and inserted at
the new index.
42. Write a Flutter widget that displays a login form with validation.
Program:
import 'package:flutter/material.dart';
class LoginForm extends StatefulWidget {
@override
_LoginFormState createState() => _LoginFormState();
}
@override
void dispose() {
_emailController.dispose();
_passwordController.dispose();
super.dispose();
}
void _submitForm() {
if (_formKey.currentState!.validate()) {
// Perform login with email and password
final email = _emailController.text;
final password = _passwordController.text;
print('Logging in with email: $email, password: $password');
}
}
Explanation:
Here, the LoginForm widget is a stateful widget that holds the form key, email and password
controllers.
● In the dispose method, the email and password controllers are disposed to prevent
memory leaks.
● In the _submitForm method, the form is validated and if validation succeeds, the
login logic is performed using the email and password entered by the user.
● In the _validateEmail and _validatePassword methods, validation logic is defined
for the email and password fields respectively.
● In the build method, a Form widget is used to hold the form and a Column widget is
used to display the email and password fields, along with an ElevatedButton widget
to submit the form. Each field is wrapped in a TextFormField widget and decorated
with a labelText property. The validator property is set to the corresponding validation
method for each field. The password field is set to obscureText to hide the password
characters.
43. Write a Flutter widget that displays a list of images fetched from
an API endpoint and allows the user to tap on them to view them in
full screen.
Program:
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
@override
void initState() {
super.initState();
_fetchImages();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Image List'),
),
body: GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
),
itemCount: _imageUrls.length,
itemBuilder: (BuildContext context, int index) {
final url = _imageUrls[index];
return GestureDetector(
onTap: () => _showImage(context, url),
child: Image.network(
url,
fit: BoxFit.cover,
),
);
},
),
);
}
}
Explanation:
Here, the ImageList widget is a stateful widget that holds the list of image URLs fetched from
the API endpoint.
● In the initState method, the _fetchImages method is called to fetch the images from
the API endpoint.
● In the _fetchImages method, an HTTP GET request is made to the API endpoint
and the response is parsed as a JSON object. The URLs of the images are extracted
from the JSON object and added to the _imageUrls list. The widget is then rebuilt to
display the images.
● In the _showImage method, a new page is pushed onto the navigation stack to
display the tapped image in full screen. The image URL is passed to the new page
as a parameter.
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Image Picker'),
),
body: Center(
child: _imageFile == null
? Text('No image selected.')
: Image.file(_imageFile!),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Select an image'),
actions: <Widget>[
TextButton(
onPressed: () {
Navigator.of(context).pop();
_pickImage(ImageSource.camera);
},
child: Text('Camera'),
),
TextButton(
onPressed: () {
Navigator.of(context).pop();
_pickImage(ImageSource.gallery);
},
child: Text('Gallery'),
),
],
);
},
);
},
tooltip: 'Pick Image',
child: Icon(Icons.add_a_photo),
),
);
}
}
Explanation:
Here, the ImagePickerWidget widget is a stateful widget that holds the selected image file.
● In the _pickImage method, an image is picked from the specified source (either the
camera or the gallery). If an image is successfully picked, the _imageFile state
variable is updated and the widget is rebuilt to display the selected image.
● In the build method, the selected image is displayed using an Image.file widget. If
no image has been selected yet, a text widget is displayed instead.
● A floating action button is used to display an alert dialog with options to select an
image from the camera or the gallery. When the user selects an option, the
_pickImage method is called with the appropriate image source.
import 'dart:async';
import 'package:flutter/material.dart';
CountdownTimerWidget({required this.duration});
@override
_CountdownTimerWidgetState createState() => _CountdownTimerWidgetState();
}
@override
void initState() {
super.initState();
_remainingSeconds = widget.duration;
}
void _startTimer() {
_isRunning = true;
_timer = Timer.periodic(Duration(seconds: 1), (timer) {
setState(() {
if (_remainingSeconds > 0) {
_remainingSeconds--;
} else {
_isRunning = false;
_timer.cancel();
}
});
});
}
void _stopTimer() {
_isRunning = false;
_timer.cancel();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Countdown Timer'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
_timerText,
style: TextStyle(fontSize: 72),
),
SizedBox(height: 32),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: _isRunning ? null : _startTimer,
child: Text('Start'),
),
SizedBox(width: 16),
ElevatedButton(
onPressed: _isRunning ? _stopTimer : null,
child: Text('Stop'),
),
],
),
],
),
),
);
}
@override
void dispose() {
_timer.cancel();
super.dispose();
}
}
Explanation:
Here, the CountdownTimerWidget widget is a stateful widget that holds the remaining
seconds and whether the timer is running or not.
● In the initState method, the _remainingSeconds state variable is set to the initial
duration passed to the widget.
● The _startTimer method is called when the user taps the start button. It sets the
_isRunning state variable to true and starts a periodic timer that decrements the
_remainingSeconds state variable by one every second. If the remaining seconds
reach zero, the timer is stopped.
● The _stopTimer method is called when the user taps the stop button. It sets the
_isRunning state variable to false and cancels the timer.
● The _timerText getter returns a string that represents the remaining time in the
format mm:ss.
● In the build method, the remaining time is displayed using a Text widget. The start
and stop buttons are displayed using ElevatedButton widgets. The start button is
disabled when the timer is running, and the stop button is disabled when the timer is
not running.
● In the dispose method, the timer is canceled when the widget is removed from the
widget tree.
Build a simple UI
You may be asked to build a simple user interface using Flutter widgets and layouts,
demonstrating your knowledge of material design principles.
Platform integration
Recruiters can ask you to integrate a Flutter app with a native device feature such as
camera, geolocation, or push notifications.
Performance optimization
The interviewer can assign you the task to optimize the performance of a Flutter app by
using techniques such as lazy loading, caching, and asynchronous programming.
● HTML Course
● React Js Course
● Javascript Course
● PHP Curse
● Power BI Course
● Tableau Course