Flutter UI Design Course Overview
Flutter UI Design Course Overview
void main() {
int num1 = 10; //declaring number1
int num2 = 3; //declaring number2
// Calculation
int sum = num1 + num2;
int diff = num1 - num2;
int mul = num1 * num2;
double div = num1 / num2; // It is double because it outputs number with
decimal.
Output:
The sum is 13
The diff is 7
The mul is 30
The div is 3.3333333333333335
import 'dart:io';
void main() {
print("Enter number:");
int? number = [Link]([Link]()!);
print("The entered number is ${number}");
}
Output:
Enter number:
50
The entered number is 50
Text Widget:
import 'package:flutter/[Link]';
// function to trigger build process
void main() => runApp(const GeeksforGeeks());
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: [Link],
appBar: AppBar(
backgroundColor: [Link],
title: const Text("welcome Screen"),
), // AppBar
body: Container(
child: const Center(
child: Text("Hello world!!"),
), // Center
), // Container
), // Scaffold
); // MaterialApp
}
}
Image Widget:
import 'package:flutter/[Link]';
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text(
'Insert Image Demo',
),
),
body: Center(
child: Column(
children: <Widget>[
[Link]('assets/images/[Link]',
height: 200,
scale: 2.5,
// color: [Link](255, 15, 147, 59),
opacity:
const
AlwaysStoppedAnimation<double>(0.5)), //[Link]
[Link](
'assets/images/[Link]',
height: 400,
width: 400,
), // [Link]
], //<Widget>[]
), //Column
), //Center
),
);
}
}
Containter Widget:
import 'package:flutter/[Link]';
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text("Container example"),
),
body: Container(
height: 200,
width: [Link],
//color: [Link],
alignment: [Link],
margin: const [Link](20),
padding: const [Link](30),
decoration: BoxDecoration(
border: [Link](color: [Link], width: 3),
),
child: const Text("Hello! i am inside a container!",
style: TextStyle(fontSize: 20)),
),
),
);
}
}
Output:
b) Implement different layout structures using Row, Column, and Stack widgets
Row Widget
import 'package:flutter/[Link]';
@override
return MaterialApp(
home: MyHomePage()
);
@override
@override
return Scaffold(
appBar: AppBar(
),
body: Row(
mainAxisAlignment: [Link],
children:<Widget>[
Container(
margin: [Link](12.0),
padding: [Link](8.0),
decoration:BoxDecoration(
borderRadius:[Link](8),
color:[Link]
),
child:
Text("[Link]",style: TextStyle(color:[Link],fontSize:25),),
),
Container(
margin: [Link](15.0),
padding: [Link](8.0),
decoration:BoxDecoration(
borderRadius:[Link](8),
color:[Link]
),
child: Text("Flutter",style:
TextStyle(color:[Link],fontSize:25),),
),
Container(
margin: [Link](12.0),
padding: [Link](8.0),
decoration:BoxDecoration(
borderRadius:[Link](8),
color:[Link]
),
child: Text("MySQL",style:
TextStyle(color:[Link],fontSize:25),),
),
);
Output:
When we run this app, we should get the UI as the below screenshot.
Column Widget:
import 'package:flutter/[Link]';
Stack Widget:
import 'package:flutter/[Link]';
void main() {
runApp(MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('GeeksforGeeks'),
backgroundColor: [Link][400],
), //AppBar
body: Center(
child: SizedBox(
width: 300,
height: 300,
child: Center(
child: Stack(
children: <Widget>[
Container(
width: 300,
height: 300,
color: [Link],
), //Container
Container(
width: 250,
height: 250,
color: [Link],
), //Container
Container(
height: 200,
width: 200,
color: [Link],
), //Container
], //<Widget>[]
), //Stack
), //Center
), //SizedBox
) //Center
) //Scaffold
) //MaterialApp
);
}
Output:
3. a) Design a responsive UI that adapts to different screen sizes.
Ans)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet"
href="[Link]
<title>Responsive UI Example</title>
</head>
<body>
<div class="container">
<header class="jumbotron text-center">
<h1>Responsive UI Example</h1>
</header>
<main>
<section class="mb-4">
<h2>Section 1</h2>
<p>This is some content for section 1.</p>
</section>
<section class="mb-4">
<h2>Section 2</h2>
<p>This is some content for section 2.</p>
</section>
</main>
Output:
header {
background-color: #333;
color: #fff;
text-align: center;
padding: 1em;
}
main {
max-width: 1200px;
margin: 0 auto;
padding: 20px;
}
section {
margin-bottom: 20px;
}
footer {
background-color: #333;
color: #fff;
text-align: center;
padding: 1em;
position: fixed;
bottom: 0;
width: 100%;
}
footer {
position: static;
}
}
</style>
<title>Responsive UI Example</title>
</head>
<body>
<div class="container">
<header class="jumbotron text-center">
<h1>Responsive UI Example</h1>
</header>
<main>
<section class="mb-4">
<h2>Section 1</h2>
<p>This is some content for section 1.</p>
</section>
<section class="mb-4">
<h2>Section 2</h2>
<p>This is some content for section 2.</p>
</section>
</main>
Output:
Ans)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Screen Navigation Example</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #f4f4f4;
}
header {
background-color: #333;
color: #fff;
text-align: center;
padding: 1em;
}
main {
max-width: 1200px;
margin: 0 auto;
padding: 20px;
}
section {
display: none;
}
footer {
background-color: #333;
color: #fff;
text-align: center;
padding: 1em;
position: fixed;
bottom: 0;
width: 100%;
}
.active {
display: block;
}
</style>
</head>
<body>
<header class="jumbotron text-center">
<h1>Screen Navigation Example</h1>
</header>
<main>
<section id="home" class="active">
<h2>Home Screen</h2>
<p>Welcome to the Home Screen.</p>
<button onclick="navigateTo('about')">Go to About</button>
</section>
<section id="about">
<h2>About Screen</h2>
<p>This is the About Screen.</p>
<button onclick="navigateTo('home')">Go to Home</button>
</section>
</main>
<script>
function navigateTo(screenId) {
// Hide all sections
[Link]('section').forEach(section => {
[Link]('active');
});
Output:
b) Implement navigation with named routes.
Ans)
import 'package:flutter/[Link]';
void main() {
runApp(MyApp());
}
import 'package:flutter/[Link]';
void main() {
runApp(MyApp());
}
void incrementCounter() {
setState(() {
counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Stateful and Stateless Example'),
),
body: Column(
mainAxisAlignment: [Link],
children: <Widget>[
CounterDisplay(counter),
SizedBox(height: 20),
CounterButton(incrementCounter),
],
),
);
}
}
CounterDisplay([Link]);
@override
Widget build(BuildContext context) {
return Text(
'Counter Value: $count',
style: TextStyle(fontSize: 20),
);
}
}
CounterButton([Link]);
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: onPressed,
child: Text('Increment Counter'),
);
}
}
Output:
b) Implement state management using set State and Provider.
import 'package:flutter/[Link]';
import 'package:provider/[Link]';
void main() {
runApp(
ChangeNotifierProvider(
create: (context) => CounterModel(),
child: MyApp(),
),
);
}
void incrementCounter() {
_counter++;
notifyListeners();
}
}
return Scaffold(
appBar: AppBar(
title: Text('State Management Example'),
),
body: Center(
child: Column(
mainAxisAlignment: [Link],
children: <Widget>[
Text(
'Counter Value: ${[Link]}',
style: TextStyle(fontSize: 20),
),
SizedBox(height: 20),
ElevatedButton(
onPressed: [Link],
child: Text('Increment Counter'),
),
],
),
),
);
}
}
Output:
6. a) Create custom widgets for specific UI elements.
Ans)
import 'package:flutter/[Link]';
class CustomButton extends StatelessWidget {
final String text;
final Function onPressed;
final Color buttonColor;
final Color textColor;
CustomButton({
required [Link],
required [Link],
[Link] = [Link],
[Link] = [Link],
});
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: () => onPressed(),
style: ButtonStyle(
backgroundColor: [Link]<Color>(buttonColor),
foregroundColor: [Link]<Color>(textColor),
),
child: Text(text),
);
}
}
Output:
b) Apply styling using themes and custom styles.
Ans)
import 'package:flutter/[Link]';
import 'package:google_fonts/google_fonts.dart';
void main() {
runApp(const MyApp());
}
@override
Widget build(BuildContext context) {
const appName = 'Custom Themes';
return MaterialApp(
title: appName,
theme: ThemeData(
useMaterial3: true,
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title,
style: [Link](context).[Link]!.copyWith(
color: [Link](context).[Link],
)),
backgroundColor: [Link](context).[Link],
),
body: Center(
child: Container(
padding: const [Link](
horizontal: 12,
vertical: 12,
),
color: [Link](context).[Link],
child: Text(
'Text with a background color',
// TRY THIS: Change the Text value
// or change the [Link](context).textTheme
// to "displayLarge" or "displaySmall".
style: [Link](context).[Link]!.copyWith(
color: [Link](context).[Link],
),
),
),
),
floatingActionButton: Theme(
data: [Link](context).copyWith(
// TRY THIS: Change the seedColor to "[Link]" or
// "[Link]".
colorScheme: [Link](
seedColor: [Link],
brightness: [Link],
),
),
child: FloatingActionButton(
onPressed: () {},
child: const Icon([Link]),
),
),
);
}
}
Output:
7. a) Design a form with various input fields.
import 'package:flutter/[Link]';
void main() {
runApp(MyApp());
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Form Example'),
),
body: Padding(
padding: [Link](16.0),
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: [Link],
children: <Widget>[
TextFormField(
controller: _nameController,
decoration: InputDecoration(
labelText: 'Name',
border: OutlineInputBorder(),
),
validator: (value) {
if (value == null || [Link]) {
return 'Please enter your name';
}
return null;
},
),
SizedBox(height: 16),
TextFormField(
controller: _emailController,
keyboardType: [Link],
decoration: InputDecoration(
labelText: 'Email',
border: OutlineInputBorder(),
),
validator: (value) {
if (value == null || [Link]) {
return 'Please enter your email';
} else if (!RegExp(r'^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$')
.hasMatch(value)) {
return 'Please enter a valid email address';
}
return null;
},
),
SizedBox(height: 16),
TextFormField(
controller: _passwordController,
obscureText: true,
decoration: InputDecoration(
labelText: 'Password',
border: OutlineInputBorder(),
),
validator: (value) {
if (value == null || [Link]) {
return 'Please enter your password';
} else if ([Link] < 6) {
return 'Password must be at least 6 characters long';
}
return null;
},
),
SizedBox(height: 16),
ElevatedButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
// Form is valid, process the data
print('Name: ${_nameController.text}');
print('Email: ${_emailController.text}');
print('Password: ${_passwordController.text}');
}
},
child: Text('Submit'),
),
],
),
),
),
);
}
}
Output:
Ans)
import 'package:flutter/[Link]';
void main() {
runApp(MyApp());
}
Output:
7. a) Add animations to UI elements using Flutter's animation framework.
Ans)
import 'package:flutter/[Link]';
void main() {
runApp(MyApp());
}
@override
void initState() {
[Link]();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Animation Example'),
),
body: Center(
child: FadeTransition(
opacity: _opacityAnimation,
child: Container(
width: 200,
height: 200,
color: [Link],
child: Center(
child: Text(
'Animated Widget',
style: TextStyle(
color: [Link],
fontSize: 20,
),
),
),
),
),
),
);
}
@override
void dispose() {
_animationController.dispose();
[Link]();
}
}
Output:
@override
void initState() {
[Link]();
_animationController = AnimationController(
vsync: this,
duration: Duration(seconds: 10),
);
_animationController.forward();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Fade Animation Example'),
),
body: Center(
child: FadeTransition(
opacity: _opacityAnimation,
child: Container(
width: 200,
height: 200,
color: [Link],
child: Center(
child: Text(
'Fade Animation',
style: TextStyle(
color: [Link],
fontSize: 20,
),
),
),
),
),
),
);
}
@override
void dispose() {
_animationController.dispose();
[Link]();
}
}
Output:
Fade Animation
Slide Animation:
import 'package:flutter/[Link]';
void main() {
runApp(MyApp());
}
@override
void initState() {
[Link]();
_animationController = AnimationController(
vsync: this,
duration: Duration(seconds: 2),
);
_slideAnimation = Tween<Offset>(
begin: Offset(-1.0, 0.0),
end: Offset(0.0, 0.0),
).animate(
CurvedAnimation(
parent: _animationController,
curve: [Link],
),
);
_animationController.forward();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Slide Animation Example'),
),
body: SlideTransition(
position: _slideAnimation,
child: Container(
width: 200,
height: 200,
color: [Link],
child: Center(
child: Text(
'Slide Animation',
style: TextStyle(
color: [Link],
fontSize: 20,
),
),
),
),
),
);
}
@override
void dispose() {
_animationController.dispose();
[Link]();
}
}
Output:
Slide Animation
Scale Animation:
import 'package:flutter/[Link]';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Scale Animation Example',
theme: ThemeData(
primarySwatch: [Link],
),
home: ScaleAnimationWidget(),
);
}
}
@override
void initState() {
[Link]();
_animationController = AnimationController(
vsync: this,
duration: Duration(seconds: 2),
);
_animationController.forward();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Scale Animation Example'),
),
body: ScaleTransition(
scale: _scaleAnimation,
child: Container(
width: 200,
height: 200,
color: [Link],
child: Center(
child: Text(
'Scale Animation',
style: TextStyle(
color: [Link],
fontSize: 20,
),
),
),
),
),
);
}
@override
void dispose() {
_animationController.dispose();
[Link]();
}
}
Output:
Ans)
import 'package:flutter/[Link]';
import 'package:http/[Link]' as http;
import 'dart:convert';
void main() {
runApp(MyApp());
}
@override
void initState() {
[Link]();
_posts = fetchPosts();
}
if ([Link] == 200) {
// If the server returns a 200 OK response,
// parse the JSON and return a list of posts.
List<dynamic> data = [Link]([Link]);
List<Post> posts = [Link]((post) => [Link](post)).toList();
return posts;
} else {
// If the server did not return a 200 OK response,
// throw an exception.
throw Exception('Failed to load posts');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('API Fetch Example'),
),
body: FutureBuilder<List<Post>>(
future: _posts,
builder: (context, snapshot) {
if ([Link] == [Link]) {
return CircularProgressIndicator();
} else if ([Link]) {
return Text('Error: ${[Link]}');
} else {
return [Link](
itemCount: [Link]!.length,
itemBuilder: (context, index) {
return ListTile(
title: Text([Link]![index].title),
subtitle: Text([Link]![index].body),
);
},
);
}
},
),
);
}
}
class Post {
final int userId;
final int id;
final String title;
final String body;
Post({
required [Link],
required [Link],
required [Link],
required [Link],
});
Output:
b) Display the fetched data in a meaningful way in the UI.
Ans)
import 'package:flutter/[Link]';
import 'package:http/[Link]' as http;
import 'dart:convert';
void main() {
runApp(MyApp());
}
@override
void initState() {
[Link]();
_posts = fetchPosts();
}
if ([Link] == 200) {
List<dynamic> data = [Link]([Link]);
List<Post> posts = [Link]((post) => [Link](post)).toList();
return posts;
} else {
throw Exception('Failed to load posts');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('API Fetch Example'),
),
body: FutureBuilder<List<Post>>(
future: _posts,
builder: (context, snapshot) {
if ([Link] == [Link]) {
return Center(child: CircularProgressIndicator());
} else if ([Link]) {
return Center(child: Text('Error: ${[Link]}'));
} else {
return PostList(posts: [Link]!);
}
},
),
);
}
}
PostList({required [Link]});
@override
Widget build(BuildContext context) {
return [Link](
itemCount: [Link],
itemBuilder: (context, index) {
return PostItem(post: posts[index]);
},
);
}
}
PostItem({required [Link]});
@override
Widget build(BuildContext context) {
return Card(
margin: [Link](10),
elevation: 3,
child: Padding(
padding: [Link](15),
child: Column(
crossAxisAlignment: [Link],
children: [
Text(
[Link],
style: TextStyle(
fontSize: 18,
fontWeight: [Link],
),
),
SizedBox(height: 10),
Text(
[Link],
style: TextStyle(fontSize: 16),
),
],
),
),
);
}
}
class Post {
final int userId;
final int id;
final String title;
final String body;
Post({
required [Link],
required [Link],
required [Link],
required [Link],
});
Ans) Unit tests are handy for verifying the behavior of a single function, method, or
class. The test package provides the core framework for writing unit tests, and the
flutter_test package provides additional utilities for testing widgets.
This recipe demonstrates the core features provided by the test package using the
following steps:
To add the test package as a dev dependency, run flutter pub add:
content_copy
flutter pub add dev:test
2. Create a test file
In this example, create two files: [Link] and counter_test.dart.
The [Link] file contains a class that you want to test and resides in the lib folder.
The counter_test.dart file contains the tests themselves and lives inside the test folder.
In general, test files should reside inside a test folder located at the root of your Flutter
application or package. Test files should always end with _test.dart, this is the
convention used by the test runner when searching for tests.
When you’re finished, the folder structure should look like this:
content_copy
counter_app/
lib/
[Link]
test/
counter_test.dart
3. Create a class to test
Next, you need a “unit” to test. Remember: “unit” is another name for a function,
method, or class. For this example, create a Counter class inside the lib/[Link]
file. It is responsible for incrementing and decrementing a value starting at 0.
content_copy
class Counter {
int value = 0;
content_copy
// Import the test package and Counter class
import 'package:counter_app/[Link]';
import 'package:test/[Link]';
void main() {
test('Counter value should be incremented', () {
final counter = Counter();
[Link]();
expect([Link], 1);
});
}
5. Combine multiple tests in a group
If you want to run a series of related tests, use the flutter_test package group function
to categorize the tests. Once put into a group, you can call flutter test on all tests in
that group with one command.
content_copy
import 'package:counter_app/[Link]';
import 'package:test/[Link]';
void main() {
group('Test start, increment, decrement', () {
test('value should start at 0', () {
expect(Counter().value, 0);
});
[Link]();
expect([Link], 1);
});
[Link]();
expect([Link], -1);
});
});
}
6. Run the tests
Now that you have a Counter class with tests in place, you can run the tests.
IntelliJ
content_copy
flutter test test/counter_test.dart
To run all tests you put into one group, run the following command from the root of
the project:
content_copy
flutter test --plain-name "Test start, increment, decrement"
This example uses the group created in section 5.
To learn more about unit tests, you can execute this command:
Ans) Flutter provides a set of debugging tools that can help you identify and fix issues
in your app. Here's a step-by-step guide on how to use these tools:
1. Flutter DevTools:
Run your app with the flutter run command.
Open DevTools by running the following command in your terminal:
bash
Open your app in a Chrome browser and connect it to DevTools by clicking on the
"Open DevTools" button in the terminal or by navigating to [Link]
DevTools provides tabs like Inspector, Timeline, Memory, and more.
2. Flutter Inspector:
Use the Flutter Inspector in your integrated development environment (IDE) like
Android Studio or Visual Studio Code.
Toggle the Inspector in Android Studio with the shortcut Alt + Shift + D
(Windows/Linux) or Option + Shift + D (Mac).
Inspect the widget tree, modify widget properties, and observe widget relationships.
3. Hot Reload:
Leverage Hot Reload to see the immediate effect of code changes without restarting
the entire app.
Press R in the terminal or use the "Hot Reload" button in your IDE.
5. Logging:
Utilize the print function to log messages to the console.
print('Debugging message');
View logs in the terminal or the "Logs" tab in DevTools.
6. Debug Paint:
Enable debug paint to visualize the layout and rendering of widgets.
Use the debugPaintSizeEnabled and debugPaintBaselinesEnabled flags.
void main() {
debugPaintSizeEnabled = true; // Shows bounding boxes of widgets
runApp(MyApp());
}
7. Memory Profiling:
Use the "Memory" tab in DevTools to analyze memory usage and identify potential
memory leaks.
Monitor object allocations and deallocations.