0% found this document useful (0 votes)
50 views99 pages

Flutter User Registration & UI Basics

The document provides a comprehensive guide on setting up and using Flutter and Dart for creating a user registration form and various applications. It includes steps for installing Dart SDK, writing basic Dart programs, exploring Flutter widgets, implementing responsive UI, navigation between screens, and understanding stateful and stateless widgets. Additionally, it covers state management using setState and Provider, with examples for each concept.

Uploaded by

reshmamaganti01
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)
50 views99 pages

Flutter User Registration & UI Basics

The document provides a comprehensive guide on setting up and using Flutter and Dart for creating a user registration form and various applications. It includes steps for installing Dart SDK, writing basic Dart programs, exploring Flutter widgets, implementing responsive UI, navigation between screens, and understanding stateful and stateless widgets. Additionally, it covers state management using setState and Provider, with examples for each concept.

Uploaded by

reshmamaganti01
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

UID Lab Record

EXPERIMENT NO - 1

Write code for a simple user registration form for an event.


1. a) Install Flutter and Dart SDK.

Dart SDK is a pre-compiled version so we have to download and extract it only. For this
follow the below-given instructions: Step 1: Download Dart SDK. Download Dart SDK
from the Dart SDK archive page.
The URL is: [Link]

Click on DART SDK to download SDK for Windows 64-Bit Architecture. The download will start and
a zip file will be downloaded. Note: To download SDK for any other OS select OS of your choice.
Step 2: Extract the downloaded zip file. Extract the contents of downloaded zip file and after
extracting contents of zip file will be as shown:

Step 3: Running Dart. Now open bin folder and type “cmd” as given below:

1
UID Lab Record

2
UID Lab Record

Command Prompt will open with our desired path of bin folder and now type dart”.

And now we are ready to use dart through bin folder but setting up the path in environment
variables will ease our task of Step3 and we can run dart from anywhere in the file system using
command prompt.
Step 4: Setting up path in environment variables. Open Environment Variables from advanced
system settings and add Path in System Variables as depicted in image:

3
UID Lab Record

4
UID Lab Record

Now we are done to use Dart from anywhere in the file system.
Step 5: Run Dart Using cmd

5
UID Lab Record

Output:
The sum is 13
The diff is 7
The mul is 30
The div is 3.3333333333333335

Reading Input from User


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

6
UID Lab Record

b) Write a simple Dart program to understand the language basics.

// [Link]

void main() {

// Variable declaration

String name = "Flutter Developer"; int age =

21;

double score = 89.5; bool

isPassed = true;

print("Hello, $name!");

print("Age: $age"); print("Score:

$score"); print("Passed: $isPassed");

// Conditional statement if (score

>= 50) {

print("You have passed the test.");

} else {

print("You have failed the test.");

}
// Loop

print("\nPrinting numbers 1 to 5:"); for (int i

= 1; i <= 5; i++) { print(i);

// Function call

int sumResult = addNumbers(10, 20); print("\nSum of 10

and 20 is: $sumResult");

// Class and object

Student student = Student("Aarav", 22); [Link]();

7
UID Lab Record

8
UID Lab Record

// Function definition

int addNumbers(int a, int b) {

return a + b;

// Class definition class

Student { String name;

int age;

// Constructor Student([Link],

[Link]);

// Method
void display() {

print("\nStudent Name: $name");

print("Student Age: $age");

9
UID Lab Record

10
UID Lab Record

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

import ‘package:flutter/[Link]';
void main() {
runApp(MyWidgetApp());

}
class MyWidgetApp extends StatelessWidget { @override

Widget build(BuildContext context) { return

MaterialApp(

title: 'Flutter Widgets Demo', home:

Scaffold(

appBar: AppBar(title: Text("Basic Widgets")), body:

SingleChildScrollView(

child: Column( children: [

// Text Widget Text(

'Hello, Flutter!',

style: TextStyle(fontSize: 24, fontWeight: [Link]),

),

SizedBox(height: 20),

// Image Widget (from network) [Link](

'[Link]
[Link]',

height: 150,

),

SizedBox(height: 20),
// Container Widget Container(

padding: [Link](16), margin:

[Link](8), color:

[Link], child: Text(

'This is inside a Container widget', style:

11
UID Lab Record

12
UID Lab Record

TextStyle(color: [Link]),

),

),

],

),

),

),

);

13
UID Lab Record

14
UID Lab Record

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

import 'package:flutter/[Link]';

void main() { runApp(MyLayoutApp());

class MyLayoutApp extends StatelessWidget { @override

Widget build(BuildContext context) { return

MaterialApp(

title: 'Layout Widgets Demo', home:

Scaffold(

appBar: AppBar(title: Text("Row, Column, Stack Example")), body:

Column(

children: [

// Row Layout Row(

mainAxisAlignment: [Link], children: [

Icon([Link], color: [Link]),

Icon([Link], color: [Link]),

Icon(Icons.star_border),

],

),

SizedBox(height: 20),

// Column Layout Column(

children: [

Text('Item 1'),

Text('Item 2'),

Text('Item 3'),

],

),

SizedBox(height: 20),

// Stack Layout Stack(

15
UID Lab Record

16
UID Lab Record

alignment: [Link], children:

Container( width: 200,

height: 200,

color: [Link][100],

),

Container( width: 100,

height: 100,

color: [Link][400],

),

Text( "Stacked!",

style: TextStyle(color: [Link], fontSize: 20),

],

],

),

),
);

17
UID Lab Record

18
UID Lab Record

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

import 'package:flutter/[Link]';
void main() { runApp(MyResponsiveApp());

}
class MyResponsiveApp extends StatelessWidget { @override

Widget build(BuildContext context) { return

MaterialApp(

title: 'Responsive UI',


home: Scaffold(

appBar: AppBar(title: Text("Responsive Design")), body:

LayoutBuilder(

builder: (context, constraints) {

if ([Link] < 600) { return

MobileLayout();

} else if ([Link] < 1200) { return

TabletLayout();

} else {

return DesktopLayout();

},

),

),

);

class MobileLayout extends StatelessWidget { @override

Widget build(BuildContext context) {

긏̂ Mobile Layout", style: TextStyle(fontSize: 20)));





return Center(child: Text("_

19
UID Lab Record

20
UID Lab Record

class TabletLayout extends StatelessWidget { @override

Widget build(BuildContext context) {


긏̂
긓ˆ

return Center(child: Text("_ 긓



_Tablet Layout", style: TextStyle(fontSize: 24)));
}

}
class DesktopLayout extends StatelessWidget { @override

Widget build(BuildContext context) {


;
_Desktop Layout", style: TextStyle(fontSize: 28)));
return Center(child: Text("□

21
UID Lab Record

22
UID Lab Record

b) Implement media queries and breakpoints for responsiveness.

import 'package:flutter/[Link]';

void main() {
runApp(MyMediaQueryApp());

class MyMediaQueryApp extends StatelessWidget { @override

Widget build(BuildContext context) { return

MaterialApp(

title: 'MediaQuery Example', home:

Scaffold(

appBar: AppBar(title: Text("MediaQuery Example")), body:

ResponsiveWidget(),

),

);

class ResponsiveWidget extends StatelessWidget { @override

Widget build(BuildContext context) {

// Get screen width and height

final screenWidth = [Link](context).[Link]; final

screenHeight = [Link](context).[Link];

String screenType;

if (screenWidth < 600) { screenType =

"Mobile";

} else if (screenWidth < 1200) { screenType =

"Tablet";

23
UID Lab Record

24
UID Lab Record

} else {
screenType = "Desktop";

return Center( child:

Column(

mainAxisAlignment: [Link], children: [

Text(

'Screen Width: ${[Link](0)} px', style:

TextStyle(fontSize: 18),

),

Text(

'Screen Height: ${[Link](0)} px', style:

TextStyle(fontSize: 18),

),

SizedBox(height: 20), Text(

'Layout: $screenType',

style: TextStyle(fontSize: 24, fontWeight: [Link]),

),

],

),

);

25
UID Lab Record

26
UID Lab Record

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


import 'package:flutter/[Link]';
void main() {
runApp(
MaterialApp(
home: FirstScreen(),
));
}
class FirstScreen extends StatelessWidget { @override
Widget build(BuildContext context) { return

Scaffold(

appBar: AppBar(title: Text('First Screen')), body: Center(

child: ElevatedButton( onPressed: () {

[Link](

context,

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

);

},

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

),

),

);

class SecondScreen extends StatelessWidget { @override

Widget build(BuildContext context) { return

Scaffold(

appBar: AppBar(title: Text('Second Screen')), body:

Center(

child: ElevatedButton( onPressed: () {

[Link](context); // Goes back to First Screen

},

27
UID Lab Record

28
UID Lab Record

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


),

),

);

29
UID Lab Record

30
UID Lab Record

b) Implement navigation with named routes.

import 'package:flutter/[Link]';
void main() {
runApp(
MaterialApp(
initialRoute: '/', routes: {
'/': (context) => FirstNamedScreen(), '/second': (context) =>

SecondNamedScreen(),

},

));

class FirstNamedScreen extends StatelessWidget {


@override

Widget build(BuildContext context) { return

Scaffold(

appBar: AppBar(title: Text('First Named Screen')), body:

Center(

child: ElevatedButton( onPressed: () {

[Link](context, '/second');

},

child: Text('Go to Second Named Screen'),

),

),

);

class SecondNamedScreen extends StatelessWidget { @override

Widget build(BuildContext context) { return

Scaffold(

appBar: AppBar(title: Text('Second Named Screen')), body: Center(

31
UID Lab Record

32
UID Lab Record

child: ElevatedButton( onPressed: () {

[Link](context); // Returns to First Named Screen

},

child: Text('Back to First Named Screen'),

),

),
);

}
}

33
UID Lab Record

34
UID Lab Record

5. a) Learn about stateful and stateless widgets.


import 'package:flutter/[Link]';
void main() => runApp(
MyStatelessApp());
class MyStatelessApp extends StatelessWidget { @override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("Stateless Widget Example")),
body: Center(
child: MyStatelessWidget(),

),

),

);

class MyStatelessWidget extends StatelessWidget { @override

Widget build(BuildContext context) { return Text(

'I am a Stateless Widget!', style:

TextStyle(fontSize: 24),

);

35
UID Lab Record

36
UID Lab Record

import 'package:flutter/[Link]';

void main() => runApp(MyStatefulApp());


class MyStatefulApp extends StatelessWidget { @override

Widget build(BuildContext context) { return

MaterialApp(

home: CounterWidget(),

);

}
class CounterWidget extends StatefulWidget {
@override

_CounterWidgetState createState() => _CounterWidgetState();

}
class _CounterWidgetState extends State<CounterWidget> { int _count

= 0;

void _incrementCounter() { setState(() {

_count++;

});

}
@override

Widget build(BuildContext context) { return

Scaffold(

appBar: AppBar(title: Text("Stateful Widget Example")), body:

Center(

child: Text( 'Count:

$_count',

style: TextStyle(fontSize: 28),

),

),

floatingActionButton: FloatingActionButton( onPressed:

_incrementCounter,

37
UID Lab Record

38
UID Lab Record

child: Icon([Link]),

),

);
}
}

39
UID Lab Record

40
UID Lab Record

b) Implement state management using set State and Provider.

import 'package:flutter/[Link]';

void main() => runApp(SetStateApp());

class SetStateApp extends StatelessWidget { @override

Widget build(BuildContext context) {

return MaterialApp(home: CounterScreen());

}
class CounterScreen extends StatefulWidget { @override
_CounterScreenState createState() => _CounterScreenState();

class _CounterScreenState extends State<CounterScreen> { int

_counter = 0;

void _increment() { setState(() {

_counter++;

});

@override

Widget build(BuildContext context) { return

Scaffold(

appBar: AppBar(title: Text("setState Example")),

body: Center(child: Text("Counter: $_counter", style: TextStyle(fontSize: 24))), floatingActionButton:

FloatingActionButton(

onPressed: _increment, child:

Icon([Link]),

),

);

41
UID Lab Record

42
UID Lab Record

Let’s go through a fully working Provider example step by step. I'll give you the complete structure
that you can copy, paste, and run directly in your Flutter project.

⬛ Step-by-Step Provider Example 껩 Step 1:

Add Provider Package Open [Link] and

add:

dependencies: flutter:
sdk: flutter provider:
^6.0.0

Then run: flutter pub get

,̀ File Structure
/lib
┣ [Link]
┗ counter_model.dart

)괚 counter_model.dart – Create the ChangeNotifier class


import 'package:flutter/[Link]';

class CounterModel extends ChangeNotifier { int _count


= 0;

int get count => _count; void

increment() {
_count++;
notifyListeners(); // This notifies all widgets listening to rebuild
}
}

괚 [Link] – Wrap with Provider and Use It



)

import 'package:flutter/[Link]'; import


'package:provider/[Link]'; import

43
UID Lab Record

44
UID Lab Record

'counter_model.dart';

void main() { runApp(


ChangeNotifierProvider(
create: (context) => CounterModel(), child:
MyProviderApp(),
),
);
}

class MyProviderApp extends StatelessWidget { @override


Widget build(BuildContext context) { return
MaterialApp(
title: 'Provider State Management', home:
CounterScreen(),
);
}
}

class CounterScreen extends StatelessWidget { @override


Widget build(BuildContext context) {
final counter = [Link]<CounterModel>(context);

return Scaffold(
appBar: AppBar(title: Text("Provider Example")), body: Center(
child: Text(
'Counter: ${[Link]}', style:
TextStyle(fontSize: 28),
),
),
floatingActionButton: FloatingActionButton( onPressed:
[Link],
child: Icon([Link]),
),
);
}
}
Output Behavior

 Counter starts from 0.


 Each time you press the + button, the number increases.
 UI automatically updates — thanks to notifyListeners() in CounterModel.

45
UID Lab Record

46
UID Lab Record

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


import 'package:flutter/[Link]';
void main() { runApp( MyCustomWidgetApp());

}
class MyCustomWidgetApp extends StatelessWidget { @override

Widget build(BuildContext context) { return

MaterialApp(

title: 'Custom Widget Demo',


const CustomInfoCard({ required

[Link], required [Link],

required [Link],

});

@override

Widget build(BuildContext context) { return Card(

margin: [Link](16), elevation: 4,

child: Padding(

padding: const [Link](20.0), child: Column(

mainAxisSize: [Link], children: [

Icon(icon, size: 50, color: [Link]),

SizedBox(height: 10),

Text(title, style: [Link](context).[Link]),

SizedBox(height: 5),

Text(description, style: [Link](context).[Link]),

],

),

),
);
}
}

47
UID Lab Record

48
UID Lab Record

b) Apply styling using themes and custom styles.

import 'package:flutter/[Link]';
void main() { runApp(MyThemedApp());

}
class MyThemedApp extends StatelessWidget { @override

Widget build(BuildContext context) {


return MaterialApp( title:

'Theme Demo', theme:

ThemeData(

colorScheme: [Link](seedColor: [Link]),

useMaterial3: true,

textTheme: TextTheme(

titleLarge: TextStyle(fontSize: 22, fontWeight: [Link]),

bodyMedium: TextStyle(fontSize: 16, color: [Link][800]),

),

),

home: ThemeExampleScreen(),

);

class ThemeExampleScreen extends StatelessWidget { @override

Widget build(BuildContext context) { return

Scaffold(

appBar: AppBar(title: Text('Theming Example')), body: Center(

child: Column(

mainAxisAlignment: [Link], children: [

Text( 'Heading',

style: [Link](context).[Link],

),

49
UID Lab Record

50
UID Lab Record

SizedBox(height: 10),
Text(

'This is body text using custom theme.',

style: [Link](context).[Link],

),

SizedBox(height: 20), Container(

padding: [Link](12),

decoration: BoxDecoration( color:

[Link].shade50,

borderRadius: [Link](12),

),

child: Text('Styled Container'),

),

],

),

),

);

51
UID Lab Record

52
UID Lab Record

7.a) Design a form with various input fields. import 'package:flutter/[Link]';

void main() => runApp(FormInputDemo());


class FormInputDemo extends StatelessWidget { @override

Widget build(BuildContext context) { return

MaterialApp(

title: 'Form UI Example', home:

Scaffold(

appBar: AppBar(title: Text("User Form UI")),


body: Padding(

padding: const [Link](16.0), child:

UserForm(),

),

),

);

}
class UserForm extends StatefulWidget { @override

_UserFormState createState() => _UserFormState();

}
class _UserFormState extends State<UserForm> { String

name = '';

String email = ''; String

password = ''; String gender =

'Male';

@override

Widget build(BuildContext context) { return

Column(

crossAxisAlignment: [Link], children: [

// Name field TextField(

decoration: InputDecoration(labelText: 'Name'), onChanged: (value) => name = value,


),

53
UID Lab Record

54
UID Lab Record

// Email field TextField(

decoration: InputDecoration(labelText: 'Email'),

keyboardType: [Link], onChanged:

(value) => email = value,

),
// Password field TextField(

decoration: InputDecoration(labelText: 'Password'), obscureText: true,

onChanged: (value) => password = value,

),

// Gender dropdown

DropdownButton<String>( value:

gender,

onChanged: (value) { setState(() {

gender = value!;

});

},

items: ['Male', 'Female', 'Other']

.map((g) => DropdownMenuItem( value: g,

child: Text(g),
))
.toList(),

),

SizedBox(height: 20),

//Submitbutton

ElevatedButton(

onPressed: () {

print('Name: $name'); print('Email:

$email'); print('Password: $password');

print('Gender: $gender');

55
UID Lab Record

56
UID Lab Record

},

child: Text('Submit'),

),

],

);

57
UID Lab Record

58
UID Lab Record

b) Implement form validation and error handling.

import 'package:flutter/[Link]';

void main() => runApp(FormValidationDemo());


class FormValidationDemo extends StatelessWidget { @override

Widget build(BuildContext context) { return

MaterialApp(

title: 'Form Validation Example', home:

Scaffold(

appBar: AppBar(title: Text("Validated Form")), body:

Padding(

padding: const [Link](16.0),


child: ValidatedUserForm(),

),

),

);

class ValidatedUserForm extends StatefulWidget { @override

_ValidatedUserFormState createState() => _ValidatedUserFormState();

}
class _ValidatedUserFormState extends State<ValidatedUserForm> { final

_formKey = GlobalKey<FormState>();

String name = ''; String email =

''; String password = ''; String

gender = 'Male';

@override

Widget build(BuildContext context) { return

Form(

key: _formKey, // Controls validation child: ListView(

59
UID Lab Record

60
UID Lab Record

children: [

// Name TextFormField(

decoration: InputDecoration(labelText: 'Name'), validator: (value) {


if (value == null || [Link]) { return

'Please enter your name';

return null;

},

onSaved: (value) => name = value!,

),

// Email TextFormField(

decoration: InputDecoration(labelText: 'Email'),

keyboardType: [Link], validator:

(value) {

if (value == null || ![Link]('@')) { return

'Enter a valid email';

return null;

},

onSaved: (value) => email = value!,

),

// Password TextFormField(

decoration: InputDecoration(labelText: 'Password'), obscureText:

true,

validator: (value) {

if (value == null || [Link] < 6) {

return 'Password must be at least 6 characters';

61
UID Lab Record

62
UID Lab Record

return null;

},

onSaved: (value) => password = value!,

),

// Gender dropdown

DropdownButtonFormField<String>( value:

gender,

decoration: InputDecoration(labelText: 'Gender'), items:

['Male', 'Female', 'Other']

.map((label) => DropdownMenuItem( value: label,

child: Text(label),

))

.toList(),

onChanged: (value) => setState(() => gender = value!),

),

SizedBox(height: 20),

// Submit Button

ElevatedButton(

onPressed: () {

if (_formKey.currentState!.validate()) {

_formKey.currentState!.save(); // Save all values

[Link](context).showSnackBar( SnackBar(content:

Text("Form submitted successfully")),

);
print('Name: $name');
print('Email: $email');
print('Password: $password');
print('Gender: $gender');
}

63
UID Lab Record

64
UID Lab Record

},

child: Text('Submit'),

),

],

),

);

}
}

65
UID Lab Record

66
UID Lab Record

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

import 'package:flutter/[Link]';
void main() => runApp(FadeAnimationApp());
class FadeAnimationApp extends StatelessWidget { @override

Widget build(BuildContext context) { return

MaterialApp(

home: FadeDemo(),

);

}
class FadeDemo extends StatefulWidget { @override

_FadeDemoState createState() => _FadeDemoState();

}
class _FadeDemoState extends State<FadeDemo> { double

opacityLevel = 1.0;

void _toggleOpacity() { setState(()

opacityLevel = opacityLevel == 1.0 ? 0.0 : 1.0;

});

}
@override
Widget build(BuildContext context) { return

Scaffold(

appBar: AppBar(title: Text("Fade Animation")), body: Center(

child: AnimatedOpacity( opacity:

opacityLevel, duration:

Duration(seconds: 1), child: Container(

width: 200,

height: 200,

color: [Link],

),

),

67
UID Lab Record

68
UID Lab Record

),

floatingActionButton: FloatingActionButton( onPressed:

_toggleOpacity,

child: Icon([Link]),

),

);

69
UID Lab Record

70
UID Lab Record

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

import 'package:flutter/[Link]';
void main() => runApp(SlideAnimationApp());
class SlideAnimationApp extends StatelessWidget {

@override

Widget build(BuildContext context) { return

MaterialApp(

home: SlideDemo(),

);

}
class SlideDemo extends StatefulWidget { @override

_SlideDemoState createState() => _SlideDemoState();

class _SlideDemoState extends State<SlideDemo> { bool moved =

false;

@override

Widget build(BuildContext context) { return

Scaffold(

appBar: AppBar(title: Text("Slide Animation")), body: Stack(

children: [ AnimatedPositioned(

duration: Duration(seconds: 1),

left: moved ? 250 : 50,

top: 100,

child: Container( width:

100,

height: 100,

color: [Link],

),

71
UID Lab Record

72
UID Lab Record

),

],

),

floatingActionButton: FloatingActionButton( onPressed:

() {

setState(() {
moved = !moved;

});

},

child: Icon(Icons.play_arrow),

),

);

73
UID Lab Record

74
UID Lab Record

9.a) Fetch data from a REST API.

import 'package:flutter/[Link]';

import 'dart:convert';
void main() => runApp(ApiSimulationApp());
class ApiSimulationApp extends StatelessWidget {

@override

Widget build(BuildContext context) { return

MaterialApp(

title: 'DartPad API Simulation', home:

PostListScreen(),

);
}

}
class Post { final int id;

final String title; final String

body;

Post({required [Link], required [Link], required [Link]});


factory [Link](Map<String, dynamic> json) { return Post(

id: json['id'], title:

json['title'],

body: json['body'],

);

}
class PostListScreen extends StatefulWidget { @override

_PostListScreenState createState() => _PostListScreenState();

}
class _PostListScreenState extends State<PostListScreen> { late

Future<List<Post>> posts;

@override
void initState() {
[Link](); posts =

fetchPosts();

75
UID Lab Record

76
UID Lab Record

Future<List<Post>> fetchPosts() async {

await [Link](Duration(seconds: 2)); // Simulate network delay String

sampleJson = '''

{"id": 1, "title": "Hello Flutter", "body": "This is a mock post."},

{"id": 2, "title": "Dart is Cool", "body": "Learning Dart is fun!"},

{"id": 3, "title": "REST API Example", "body": "This simulates an API."}

''';

List<dynamic> jsonData = jsonDecode(sampleJson);

return [Link]((item) => [Link](item)).toList();

}
@override

Widget build(BuildContext context) { return

Scaffold(

appBar: AppBar(title: Text('Posts List (Simulated)')), body:

FutureBuilder<List<Post>>(

future: posts,

builder: (context, snapshot) { if

([Link]) { return ListView(

children: [Link]!.map((post) { return Card(

margin: [Link](10),
child: ListTile(

title: Text([Link]), subtitle:

Text([Link]),

),

);

}).toList(),

);

77
UID Lab Record

78
UID Lab Record

} else if ([Link]) {

return Center(child: Text('Error: ${[Link]}'));

return Center(child: CircularProgressIndicator());

},

),

);

79
UID Lab Record

80
UID Lab Record

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

import 'package:flutter/[Link]';

import 'dart:convert';
void main() => runApp(ApiDisplayApp());

class ApiDisplayApp extends StatelessWidget { @override

Widget build(BuildContext context) { return

MaterialApp(

title: 'API Display UI', home:

PostListScreen(),

);
}
}
class Post { final int id;

final String title; final String

body;

Post({required [Link], required [Link], required [Link]});


factory [Link](Map<String, dynamic> json) { return Post(

id: json['id'], title:

json['title'],

body: json['body'],

);

class PostListScreen extends StatefulWidget { @override

_PostListScreenState createState() => _PostListScreenState();

}
class _PostListScreenState extends State<PostListScreen> { late

Future<List<Post>> posts;

@override

void initState() { [Link]();

final post = [Link]![index]; return Card(

81
UID Lab Record

82
UID Lab Record

elevation: 4, child: ListTile(

title: Text([Link],

style: TextStyle(fontWeight: [Link])), subtitle:

Text([Link]),

),

);

},

);

} else if ([Link]) {

return Center(child: Text('Error loading data.'));

} else {

return Center(child: CircularProgressIndicator());

},

),

);

83
UID Lab Record

84
UID Lab Record

10.a) Write unit tests for UI components.


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

⬛ 10(a) Write Unit Tests for UI Components

In Flutter, we typically write widget tests (UI component tests) using the flutter_test package.

DartPad does not support test files. You must run this in VS Code / Android Studio / terminal.

¸

/5Q Step 1: Create a simple UI component

Create a new widget to test (e.g., a counter screen):

// lib/counter_widget.dart

import

'package:flutter/[Link]';

class CounterWidget extends StatefulWidget { @override


_CounterWidgetState createState() => _CounterWidgetState();
}

class _CounterWidgetState extends State<CounterWidget> { int count


= 0;

void increment() { setState(() =>


count++);
}

@override
Widget build(BuildContext context) { return
Column(
children: [
Text('Count: $count', key: Key('counterText')),
ElevatedButton(
key: Key('incrementButton'), onPressed:
increment,
child: Text('Increment'),
),
],
);
}
}

^
`
Step 2: Write Unit/Widget Test

Create this in test/counter_widget_test.dart:

85
UID Lab Record

86
UID Lab Record

import 'package:flutter/[Link]';
import 'package:flutter_test/flutter_test.dart';
import 'package:your_app/counter_widget.dart'; // Adjust import path

void main() {
testWidgets('Counter increments when button is pressed', (WidgetTester tester) async { await
[Link](
MaterialApp(home: Scaffold(body: CounterWidget())),
);

// Initial state
expect([Link]('Count: 0'), findsOneWidget);

// Tap the button


await [Link]([Link](Key('incrementButton')));
await [Link](); // Rebuild the widget// Check
updated state expect([Link]('Count: 1'),
findsOneWidget);
});
}

Run the Test In terminal:

flutter test

You should see:

+1: All tests passed!

10(b) Use Flutter's Debugging Tools

Here’s how you can debug and fix issues in Flutter:

Tool Usage
Flutter DevTools Memory, widget tree, performance profiling
debugPrint() Log internal values in your widget/state
flutter run --debug Runs app in debug mode with hot reload
breakpoints (VS Code/Android Studio) Inspect variable state at runtime
flutter analyze Check for errors, lints, dead code

*
˛ Common Debugging Tips:

 Use print() or debugPrint() to inspect values during state changes.


 If your widget is not updating, check if you're calling setState() properly.
 Use hot reload frequently to test UI updates.
 Use Flutter Inspector in DevTools to see widget hierarchy and constraints.
 Use flutter analyze to catch potential logic issues.

87
UID Lab Record

88
UID Lab Record

˙Q
•Example Fix: Widget not rebuilding?

// + Common mistake var count


= 0; onPressed: () {
count++; // UI won't update
};
// Correct setState(()
{ count++;
});

89
UID Lab Record

90
UID Lab Record

Content Beyond Syllabus:

1. Integrate SQL – LITE Database


import 'package:flutter/[Link]';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Fake SQLite in DartPad',
theme: ThemeData(primarySwatch: [Link]),
home: MyHomePage(),
);
}
}

class Person {
int id;
String name;
int age;
Person({required [Link], required [Link], required [Link]});
}

class MyHomePage extends StatefulWidget {


@override
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {


List<Person> _fakeDb = [];
int _nextId = 1;

final _nameController = TextEditingController();


final _ageController = TextEditingController();

// Add a new record


void _addRecord() {
final name = _nameController.[Link]();
final ageText = _ageController.[Link]();
if ([Link] || [Link]) return;

final age = [Link](ageText);


if (age == null) return;

setState(() {
_fakeDb.add(Person(id: _nextId++, name: name, age: age));
_nameController.clear();
_ageController.clear();
});
}

91
UID Lab Record

92
UID Lab Record

// Delete a record by id
void _deleteRecord(int id) {
setState(() {
_fakeDb.removeWhere((person) => [Link] == id);
});
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Fake SQLite in DartPad'),
),
body: Padding(
padding: const [Link](16),
child: Column(
children: [
// Input fields
TextField(
controller: _nameController,
decoration: InputDecoration(labelText: 'Name'),
),
TextField(
controller: _ageController,
decoration: InputDecoration(labelText: 'Age'),
keyboardType: [Link],
),
SizedBox(height: 10),
ElevatedButton(
onPressed: _addRecord,
child: Text('Add Record'),
),
SizedBox(height: 20),

// List of records
Expanded(
child: _fakeDb.isEmpty
? Center(child: Text('No records yet'))
: [Link](
itemCount: _fakeDb.length,
itemBuilder: (context, index) {
final person = _fakeDb[index];
return ListTile(
title: Text([Link]),
subtitle: Text('Age: ${[Link]}'),
trailing: IconButton(
icon: Icon([Link]),
onPressed: () => _deleteRecord([Link]),
),
);
},
),
),
],
),

93
UID Lab Record

94
UID Lab Record

2. Perform Basic CRUD operations

import 'package:flutter/[Link]';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {


@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Basic CRUD Demo',
theme: ThemeData(primarySwatch: [Link]),
home: CrudHomePage(),
);
}
}

class Person {
int id;
String name;
int age;
Person({required [Link], required [Link], required [Link]});
}

class CrudHomePage extends StatefulWidget {


@override
_CrudHomePageState createState() => _CrudHomePageState();
}

class _CrudHomePageState extends State<CrudHomePage> {


List<Person> _people = [];
int _nextId = 1;

final _nameController = TextEditingController();


final _ageController = TextEditingController();

Person? _editingPerson;

void _clearInputs() {
_nameController.clear();
_ageController.clear();
_editingPerson = null;
}

void _addOrUpdateRecord() {
final name = _nameController.[Link]();
final ageText = _ageController.[Link]();
if ([Link] || [Link]) return;

final age = [Link](ageText);


if (age == null) return;

setState(() {
if (_editingPerson == null) {

95
UID Lab Record

96
UID Lab Record

// Create
_people.add(Person(id: _nextId++, name: name, age: age));
} else {
// Update
_editingPerson!.name = name;
_editingPerson!.age = age;
}
_clearInputs();
});
}

void _deleteRecord(int id) {


setState(() {
_people.removeWhere((p) => [Link] == id);
if (_editingPerson != null && _editingPerson!.id == id) {
_clearInputs();
}
});
}

void _startEdit(Person person) {


setState(() {
_editingPerson = person;
_nameController.text = [Link];
_ageController.text = [Link]();
});
}

@override
Widget build(BuildContext context) {
final isEditing = _editingPerson != null;
return Scaffold(
appBar: AppBar(
title: Text('Basic CRUD Demo'),
),
body: Padding(
padding: const [Link](16),
child: Column(
children: [
// Input Fields
TextField(
controller: _nameController,
decoration: InputDecoration(labelText: 'Name'),
),
TextField(
controller: _ageController,
decoration: InputDecoration(labelText: 'Age'),
keyboardType: [Link],
),
SizedBox(height: 10),
Row(
children: [
ElevatedButton(
onPressed: _addOrUpdateRecord,

97
UID Lab Record

98
UID Lab Record

child: Text(isEditing ? 'Update Record' : 'Add Record'),


),
SizedBox(width: 10),
if (isEditing)
ElevatedButton(
onPressed: () {
setState(() {
_clearInputs();
});
},
child: Text('Cancel'),
style: [Link](backgroundColor: [Link]),
),
],
),
SizedBox(height: 20),

// List of records
Expanded(
child: _people.isEmpty
? Center(child: Text('No records yet'))
: [Link](
itemCount: _people.length,
itemBuilder: (context, index) {
final person = _people[index];
return ListTile(
title: Text([Link]),
subtitle: Text('Age: ${[Link]}'),
onTap: () => _startEdit(person),
trailing: IconButton(
icon: Icon([Link]),
onPressed: () => _deleteRecord([Link]),
),
);
},
),
),
],
),
),
);
}
}

99

You might also like