Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
17 views

Basic Flutter Assignment

Uploaded by

hungptfpt2004
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Basic Flutter Assignment

Uploaded by

hungptfpt2004
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

Flutter

Training Assignments
R2S Academy Flutter Internal Use

Creating Simple Application


Overview

In this practice, you will learn how to create a Simple Hello World Fuller application.

Tasks

1. Open Android Studio and select Select Flutter, verify the Flutter SDK path with the SDK’s
location. Then click Next.

2. Enter a project name (for example, myapp). Select Application as the project type. Then
click Finish.

R2S Academy Internal use 2/46


R2S Academy Flutter Internal Use
3. Wait for Android Studio to create the project.

4. Open the main.dart file and modify the given code below:

1. import 'my_app.dart';
2.
3. void main() {
4. runApp(const MyApp());
5. }

5. Create Flutter Widget

Type MyApp

R2S Academy Internal use 3/46


R2S Academy Flutter Internal Use
Open the my_app.dart file and write the given code below:

1. class MyApp extends StatelessWidget {


2. const MyApp({super.key});
3.
4. @override
5. Widget build(BuildContext context) {
6. return MaterialApp(
7. home: _HomePage(),
8. );
9. }
10. }
11.
12. class _HomePage extends StatelessWidget {
13. @override
14. Widget build(BuildContext context) {
15. return Scaffold(
16. appBar: AppBar(title: const Text('Flutter Demo Home Page'),),
17. body: const Center(
18. child: Text('Hello World'),
19. ),
20. );
21. }
22. }

6. Run the app

- Locate the main Android Studio toolbar

- In the target selector, select an Android device for running the app. If none are listed as available,
select Tools > AVD Manager and create one there.

R2S Academy Internal use 4/46


R2S Academy Flutter Internal Use
- Click the run icon in the toolbar. After the app build completes, you’ll see the starter app on your
device.

Android emulator iOS simulator

Working with Widgets


Overview

In this practice, you will learn about Flutter platform specific widgets.

Tasks

1. Open the Android Studio, navigate to the project folder and create file named
pavlova_recipe.dart

2. Open the pavlova_recipe.dart file and write code below

R2S Academy Internal use 5/46


R2S Academy Flutter Internal Use
1. class PavlovaRecipe extends StatelessWidget {
2. const PavlovaRecipe({super.key}) ;
3.
4. @override
5. Widget build(BuildContext context) {
6. return MaterialApp(
7. home: buildHomePage(),
8. );
9. }
10.
11. Widget buildHomePage() {
12. const titleText = Padding(
13. padding: EdgeInsets.only(bottom: 10),
14. child: Text(
15. 'Strawberry Pavlova',
16. style: TextStyle(
17. fontWeight: FontWeight.w800,
18. letterSpacing: 0.5,
19. fontSize: 25,
20. ),
21. ),
22. );
23.
24. const subTitle = Text(
25. 'Pavlova is a meringue-based dessert named after the Russian ballerina '
26. 'Anna Pavlova. Pavlova features a crisp crust and soft, light inside, '
27. 'topped with fruit and whipped cream.',
28. textAlign: TextAlign.center,
29. style: TextStyle(
30. fontFamily: 'Georgia',
31. fontSize: 20,
32. ),
33. );
34.
35. // #docregion ratings, stars
36. var stars = Row(
37. mainAxisSize: MainAxisSize.min,
38. children: [
39. Icon(Icons.star, color: Colors.green[500]),
40. Icon(Icons.star, color: Colors.green[500]),

R2S Academy Internal use 6/46


R2S Academy Flutter Internal Use
41. Icon(Icons.star, color: Colors.green[500]),
42. const Icon(Icons.star, color: Colors.black),
43. const Icon(Icons.star, color: Colors.black),
44. ],
45. );
46.
47. // #enddocregion stars
48. var ratings = Container(
49. padding: const EdgeInsets.all(20),
50. child: Row(
51. mainAxisAlignment: MainAxisAlignment.spaceEvenly,
52. children: [
53. stars,
54. const Text(
55. '170 Reviews',
56. style: TextStyle(
57. color: Colors.black,
58. fontWeight: FontWeight.w800,
59. fontFamily: 'Roboto',
60. letterSpacing: 0.5,
61. fontSize: 20,
62. ),
63. ),
64. ],
65. ),
66. );
67. // #enddocregion ratings
68.
69. // #docregion iconList
70. const descTextStyle = TextStyle(
71. color: Colors.black,
72. fontWeight: FontWeight.w800,
73. fontFamily: 'Roboto',
74. letterSpacing: 0.5,
75. fontSize: 18,
76. height: 2,
77. );
78.
79. // DefaultTextStyle.merge() allows you to create a default text
80. // style that is inherited by its child and all subsequent children.

R2S Academy Internal use 7/46


R2S Academy Flutter Internal Use
81. final iconList = DefaultTextStyle.merge(
82. style: descTextStyle,
83. child: Container(
84. padding: const EdgeInsets.all(20),
85. child: Row(
86. mainAxisAlignment: MainAxisAlignment.spaceEvenly,
87. children: [
88. Column(
89. children: [
90. Icon(Icons.kitchen, color: Colors.green[500]),
91. const Text('PREP:'),
92. const Text('25 min'),
93. ],
94. ),
95. Column(
96. children: [
97. Icon(Icons.timer, color: Colors.green[500]),
98. const Text('COOK:'),
99. const Text('1 hr'),
100. ],
101. ),
102. Column(
103. children: [
104. Icon(Icons.restaurant, color: Colors.green[500]),
105. const Text('FEEDS:'),
106. const Text('4-6'),
107. ],
108. ),
109. ],
110. ),
111. ),
112. );
113. // #enddocregion iconList
114.
115. final mainImage = Image.asset(
116. 'images/pavlova.jpeg',
117. );
118.
119. // #docregion mainColumn
120. final mainColumn = Container(

R2S Academy Internal use 8/46


R2S Academy Flutter Internal Use
121. padding: const EdgeInsets.all(20),
122. child: Column(
123. children: [
124. titleText,
125. subTitle,
126. ratings,
127. iconList,
128. //mainImage,
129. Expanded(child: mainImage),
130. ],
131. ),
132. );
133. // #enddocregion mainColumn
134.
135. return Scaffold(
136. appBar: AppBar(
137. title: const Text('Pavlova Recipe'),
138. ),
139. // #docregion body
140. body: mainColumn,
141. // #enddocregion body
142. );
143. }

- Implement the mainImage at buildHomePage

+ Create an images directory at the top of the project and add pavlova.jpeg

+ Update the pubspec.yaml file to include an assets tag. This makes the image available to your
code.

R2S Academy Internal use 9/46


R2S Academy Flutter Internal Use

3. Run the app

Android emulator iOS simulator

Building layouts
Overview

In this practice, you'll create a simple mobile Flutter app.

Tasks

1. Open the Android Studio, navigate to the project folder

+ Create Flutter Widget

R2S Academy Internal use 10/46


R2S Academy Flutter Internal Use

+ Type named StartupNamer and press enter

2. Replace the contents of lib/startup_namer.dart

R2S Academy Internal use 11/46


R2S Academy Flutter Internal Use

3. Use an external package

In this step, you'll start using an open-source package named english_words, which contains a few
thousand of the most-used English words, plus some utility functions.

Add the english_words package as a dependency of this app:

+ english_words: ^4.0.0

+ Click ‘Pub get’

R2S Academy Internal use 12/46


R2S Academy Flutter Internal Use
4. Add a stateful widget

+ In lib/startup_namer.dart, start typing stful, the editor asks if you want to create a Stateful widget.
Press Return to accept. The boilerplate code for two classes appears, and the cursor is positioned
for you to enter the name of your stateful widget. Enter RandomWords as the name of your
widget. As you can see in the code below

+ Update the _RandomWordsState:

R2S Academy Internal use 13/46


R2S Academy Flutter Internal Use
5. Update the build method for StartupNamer

- Final source code

R2S Academy Internal use 14/46


R2S Academy Flutter Internal Use
6. Run the app

Android emulator iOS simulator


Extra tasks

Android emulator iOS simulator

R2S Academy Internal use 15/46


R2S Academy Flutter Internal Use

Using navigation and routing


Overview
In this practice, you'll extend a basic, mobile Flutter app to include interactivity. You'll also create a
second page (called a route) that the user can navigate to.

Tasks
1. Get the starting app
+ Open the Android Studio and add the english_words package as a dependency of this app:
english_words: ^4.0.0

2. Write code
+ Delete all of the code from lib/startup_namer.dart. Replace it with the follow code

R2S Academy Internal use 16/46


R2S Academy Flutter Internal Use

R2S Academy Internal use 17/46


R2S Academy Flutter Internal Use

+ Navigate to a new screen

R2S Academy Internal use 18/46


R2S Academy Flutter Internal Use
+ Final code

3. Run the app

Android emulator iOS simulator


R2S Academy Internal use 19/46
R2S Academy Flutter Internal Use
Extra tasks
+ In this tasks, create a list of todos. When a todo is tapped, navigate to a new screen (widget) that
displays information about the todo. This recipe uses the following steps:

1. Define a todo class.


2. Display a list of todos.
3. Create a detail screen that can display information about a todo.
4. Navigate and pass data to the detail screen.
+ Run the app

Android emulator iOS simulator

R2S Academy Internal use 20/46


R2S Academy Flutter Internal Use
Adding interactivity to your Flutter app
Overview
What you’ll learn

• How to respond to taps.

• How to create a custom widget.

• The difference between stateless and stateful widgets.

The building layouts tutorial showed you how to create the layout for the following screenshot.

When the app first launches, the star is solid red, indicating that this lake has previously been
favorited. The number next to the star indicates that 41 people have favorited this lake. After
completing this tutorial, tapping the star removes its favorited status, replacing the solid star with an
outline and decreasing the count. Tapping again favorites the lake, drawing a solid star and
increasing the count.

Tasks

R2S Academy Internal use 21/46


R2S Academy Flutter Internal Use
1. Subclass StatefulWidget

2. Subclass State

+ The class also defines a build() method, which creates a row containing a red IconButton,
and Text. You use IconButton (instead of Icon) because it has an onPressed property that defines
the callback function (_toggleFavorite) for handling a tap.

R2S Academy Internal use 22/46


R2S Academy Flutter Internal Use
+ The _toggleFavorite() method

3. Plug the stateful widget into the widget tree

R2S Academy Internal use 23/46


R2S Academy Flutter Internal Use
4. Run the app

Extra tasks

R2S Academy Internal use 24/46


R2S Academy Flutter Internal Use
Forms
Overview
What you’ll learn

• Build a form with validation.


• Create and style a text field.
• Retrieve the value of a text field.
Tasks

R2S Academy Internal use 25/46


R2S Academy Flutter Internal Use
1. class LoginPage extends StatelessWidget {
2. const LoginPage({super.key});
3.
4. @override
5. Widget build(BuildContext context) {
6. return MaterialApp(
7. home: buildHomePage(),
8. );
9. }
10.
11. Widget buildHomePage() {
12. return Scaffold(
13. appBar: AppBar(
14. title: const Text('Login Form'),
15. ),
16. body: const _LoginForm(),
17. );
18. }
19. }
20.
21. class _LoginForm extends StatefulWidget {
22. const _LoginForm({super.key});
23.
24. static const String email = "kyle@r2s.com.vn";
25. static const String password = "Abc@12345";
26.
27. @override
28. State<_LoginForm> createState() => _LoginFormState();
29. }
30.
31. class _LoginFormState extends State<_LoginForm> {
32. final _formKey = GlobalKey<FormState>();
33. TextEditingController emailController = TextEditingController();
34. TextEditingController passwordController = TextEditingController();
35.
36. @override
37. Widget build(BuildContext context) {
38. return Form(
39. key: _formKey,
40. child: Padding(

R2S Academy Internal use 26/46


R2S Academy Flutter Internal Use
41. padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 16),
42. child: Column(
43. crossAxisAlignment: CrossAxisAlignment.center,
44. children: [
45. Padding(
46. padding:
47. const EdgeInsets.symmetric(horizontal: 8, vertical: 16),
48. child: TextFormField(
49. controller: emailController,
50. decoration: const InputDecoration(
51. border: OutlineInputBorder(), labelText: "Email"),
52. validator: (value) {
53. if (value == null || value.isEmpty) {
54. return 'Please enter your email';
55. }
56. return null;
57. },
58. ),
59. ),
60. Padding(
61. padding:
62. const EdgeInsets.symmetric(horizontal: 8, vertical: 16),
63. child: TextFormField(
64. controller: passwordController,
65. obscureText: true,
66. decoration: const InputDecoration(
67. border: OutlineInputBorder(), labelText: "Password"),
68. validator: (value) {
69. if (value == null || value.isEmpty) {
70. return 'Please enter your password';
71. }
72. return null;
73. },
74. ),
75. ),
76. Padding(
77. padding:
78. const EdgeInsets.symmetric(horizontal: 8, vertical: 16.0),
79. child: Center(
80. child: ElevatedButton(

R2S Academy Internal use 27/46


R2S Academy Flutter Internal Use
81. onPressed: _submit,
82. child: const Text('Submit'),
83. ),
84. ),
85. ),
86. ],
87. ),
88. ),
89. );
90. }
91.
92. void _submit() {
93. if (_formKey.currentState!.validate()) {
94. if (emailController.text == _LoginForm.email &&
95. passwordController.text == _LoginForm.password) {
96. Navigator.push(
97. context,
98. MaterialPageRoute(
99. builder: (context) => HomePage(
100. email: emailController.text,
101. )),
102. );
103. } else {
104. ScaffoldMessenger.of(context).showSnackBar(
105. const SnackBar(
106. content: Text('Invalid Credentials')),
107. );
108. }
109. } else {
110. ScaffoldMessenger.of(context).showSnackBar(
111. const SnackBar(content: Text('Please fill input')),
112. );
113. }
114. }
115.}
116.
117.class HomePage extends StatelessWidget {
118. const HomePage({super.key, required this.email});
119.
120. final String email;

R2S Academy Internal use 28/46


R2S Academy Flutter Internal Use
121.
122. @override
123. Widget build(BuildContext context) {
124. return Scaffold(
125. appBar: AppBar(
126. title: const Text('Home Page'),
127. ),
128. body: Column(
129. children: [
130. Text(email),
131. Center(
132. child: ElevatedButton(
133. onPressed: () {
134. Navigator.pop(context);
135. },
136. child: const Text("Go back!"),
137. ),
138. ),
139. ],
140. ));
141. }
142.}
143.

R2S Academy Internal use 29/46


R2S Academy Flutter Internal Use
Extra tasks

Tips:

• Using Stack class: https://api.flutter.dev/flutter/widgets/Stack-class.html

• Using GestureDetector class

• Using Container class

R2S Academy Internal use 30/46


R2S Academy Flutter Internal Use
Animations
Overview
What you’ll learn
• Implicit animations
• Explicit animations
Tasks
1. Implicit animations
+ UI using an implicitly animated widget called AnimatedOpacity
The following lab shows how to add a fade-in effect to existing UI using an implicitly animated
widget called AnimatedOpacity. It consists of a Material App home screen containing:
• A photograph of an owl.
• One Show details button that does nothing when clicked.
• Description text of the owl in the photograph.

R2S Academy Internal use 31/46


R2S Academy Flutter Internal Use
Run the app

R2S Academy Internal use 32/46


R2S Academy Flutter Internal Use
+ Using the AnimatedContainer widget

R2S Academy Internal use 33/46


R2S Academy Flutter Internal Use

Run the app

R2S Academy Internal use 34/46


R2S Academy Flutter Internal Use
2. Explicit animations
+ Code

+ Run the app

R2S Academy Internal use 35/46


R2S Academy Flutter Internal Use
Extra tasks
Task: Use SlideTransition to animate when navigating

Tips

R2S Academy Internal use 36/46


R2S Academy Flutter Internal Use
Persist data with SQLite
Overview
In this lab, we are going to build a small Flutter app that uses SQLite to persist data.
The app has a floating button that can be used to show a bottom sheet. That bottom sheet contains 2
text fields corresponding to “title” and “description”. These text fields are used to create a new
“item” or update an existing “item”.
The saved “items” are fetched from the SQLite database and displayed with a list view. There are an
update button and a delete button associated with each “item”.
Database Structure
We are going to create an SQLite database called demo.db. It has only a single table named items.
Below is the structure of the table:

Column Type Description

The id of an item and


id INTEGER
auto increment

title TEXT The name of an item

description TEXT The detail of an item

The time that the item


was created. It will be
createdAt TIMESTAMP
automatically added by
SQLite

R2S Academy Internal use 37/46


R2S Academy Flutter Internal Use
Tasks
1. Create a new Flutter project.
+ In the lib folder, add a new file named sql_helper.dart and item.dart

+ In the lib folder, add a new Flutter Widget file named items_screen.dart
+ The project structure:

+ Install the sqflite plugin (sqflite: ^2.1.0+1)

R2S Academy Internal use 38/46


R2S Academy Flutter Internal Use

2. Full code in item.dart

3. Full code in sql_helper.dart

R2S Academy Internal use 39/46


R2S Academy Flutter Internal Use

R2S Academy Internal use 40/46


R2S Academy Flutter Internal Use

4. Full code in item_screen.dart

R2S Academy Internal use 41/46


R2S Academy Flutter Internal Use

R2S Academy Internal use 42/46


R2S Academy Flutter Internal Use

R2S Academy Internal use 43/46


R2S Academy Flutter Internal Use

R2S Academy Internal use 44/46


R2S Academy Flutter Internal Use

Run the app

R2S Academy Internal use 45/46


R2S Academy Flutter Internal Use
Extra tasks

Database Structure
You are going to create an SQLite database called news.db. It has only a single table
named account. Below is the structure of the table:

Column Type Description

username TEXT Primary key

password TEXT

email TEXT

Boolean values are stored as integers 0 (female)


gender INTEGER
and 1 (male)

The time that the item was created. It will be


createdAt TIMESTAMP
automatically added by SQLite

--THE END—

R2S Academy Internal use 46/46

You might also like