Bahir Dar University - Mobile Application Development - Chapter 3: Flutter Basics PDF
Document Details
![SubstantiveSerenity9840](https://quizgecko.com/images/avatars/avatar-13.webp)
Uploaded by SubstantiveSerenity9840
Bahir Dar University
false
Addis A
Tags
Summary
This document is a presentation or lecture material covering Chapter 3 of a Mobile Application Development course. It details fundamental concepts and examples regarding Flutter widgets. It also includes an overview of various input and form-related widgets.
Full Transcript
Bahir Dar University-BiT-Faculty of Computing Course Name:-Mobile Application Development Chapter 3: Flutter Basics compiled by Addis A MOBILE APPLICATION 1 Understanding Widgets MOBILE APPLICATION 2 DEVELOP...
Bahir Dar University-BiT-Faculty of Computing Course Name:-Mobile Application Development Chapter 3: Flutter Basics compiled by Addis A MOBILE APPLICATION 1 Understanding Widgets MOBILE APPLICATION 2 DEVELOPMENT Understanding Widgets A widget is a key component of the user interface (UI) in Flutter.Widgets are used to describeUI application’s elements, the and layout of your structure, such as buttons text fields, images, containers, and more. The UI is rebuilt when the widget tree changes because Flutter is built on a reactive architecture. MOBILE APPLICATION 3 DEVELOPMENT Understanding Widgets Widgets Are Immutable: Widgets in Flutter are immutable, which means once you create a widget, you cannot modify its properties directly. Instead, when you want to make changes to the UI, you typically create a new widget with the desired changes. Widget Tree: Flutter apps are constructed using a hierarchy of widgets, known as the widget tree. At the root of the tree is the MaterialApp or CupertinoApp, which defines the overall structure of the app. Within this tree, widgets nest inside one another to create complex UIs. MOBILE APPLICATION 4 DEVELOPMENT Understanding Widgets The below image is a simple visual representation of the widget tree. MOBILE APPLICATION 5 DEVELOPMENT Understanding Widgets We can create the Flutter widget like this: Class ImageWidget extends StatelessWidget { // Class Stuff } MOBILE APPLICATION 6 DEVELOPMENT Understanding Widgets Hello World Example import @override 'package:flutter/material.dart'; Widget build(BuildContext context) { return Scaffold( class MyHomePage extends appBar: AppBar( StatelessWidget { MyHomePage({Key title: Text(this.title), ), key, this.title}) : super(key: key); body: Center( // This widget is the home page of your child: Text('Hello World'), application. ), ); final String } title; } MOBILE APPLICATION 7 DEVELOPMENT Types of Widget We can split the Flutter widget into two categories: Visible (Output and Input) Invisible (Layout and Control) MOBILE APPLICATION 8 DEVELOPMENT Text A Text widget holds some text to display on the screen. We can align the text widget by using textAlign property, and style property allow the customization of Text that includes font, font weight, font style, letter spacing, color, and many more. MOBILE APPLICATION 9 DEVELOPMENT Text The most common properties of the Text widget are as follows: style: A class that composes the styling of a text. It exposes properties that allow changing the text color, background, font line height, font size, and so on. textAlign: Controls the text horizontal alignment, giving options such as center aligned or justified, for example. maxLines: Allows specifying a maximum number of lines for the text that will be truncated if the limit is exceeded. overflow: Will define how the text will be truncated on overflows, giving options such as specifying a max-lines limit. MOBILE APPLICATION 10 DEVELOPMENT Text Widget build(BuildContext context) { Simple Text Widget return MaterialApp( home: import Scaffold( a 'package:flutter/material.dart' ppBar: ; AppBar( titl void main() => e: Text( 'Hello runApp(MyApp()); Flutter', class MyApp extends style: StatelessWidget } TextStyle(c } olor: { @override Colors.blue , fontSize: 20), )), ), MOBILE APPLICATION 11 DEVELOPMENT ); Text class MyApp extends body: Center( StatelessWidget { @override child: Text( Widget build(BuildContext 'Hello, Flutter! Welcome to the world of cross- context) { platform mobile return MaterialApp( h development. Let\'s build beautiful UIs!', style: ome: Scaffold( TextStyle( f appBar: title: Text('Text Widget ontSize: Example'), AppBar( ) 20, , fontWeight: FontWeight.bold, color: Colors.blue, ), textAlign: TextAlign.center, overflow: TextOverflow.ellipsis, 1 M }OBILE APPLICATION 2 Text:Using RichText for Complex Styling class MyApp extends StatelessWidget { body: Center( child: @override RichText( te xt: TextSpan( Widget build(BuildContext children: context) { return [ TextSpan( text: MaterialApp( 'Hello, ', style: home: Scaffold( TextStyle( f appBar: AppBar( ontSize: 20, color: title: Text('RichText Widget Colors.blac Example'), k, ), ), ), TextSpan( text: 'Flutter!', style: TextStyle( f MOBILE APPLICATION 13 DEVELOPMENT ontSize: 20, Image class MyApp extends body: StatelessWidget { Center( @override child: Widget build(BuildContext Image( context) { image: return AssetIm MaterialApp( age('ass ets/cat.p home: ng'), // Scaffold( app Replace Bar: AppBar( 'image_example.png' with your title: image asset path width: Text('Image 200, // Set width of the image Widget height: 200, // Set height of Example'), the image ), fit: BoxFit.contain, // Set how the image should be DEVELOPMENT inscribed into the space MOBILE APPLICATION 14 Ico n class MyApp extends StatelessWidget { body: Center( child: Icon( @override Icons.favorite, // Specifies the icon to Widget build(BuildContext be displayed context) { size: 50, // Sets the size of the icon return MaterialApp( color: Colors.red, // Sets the color of the icon home: Scaffold( ), appBar: AppBar( ), title: Text('Icon Widget ), Example'), } ); ), } MOBILE APPLICATION 15 DEVELOPMENT The Scaffold widget the Scaffold widget in Flutter serves as a structural component for implementing basic material design visual layouts. It provides an easy way to implement the most common elements of a typical mobile application, such as an app bar, floating action button, drawer, and bottom navigation bar. MOBILE APPLICATION 16 DEVELOPMENT The Scaffold widget class MyHomePage extends StatelessWidget { body: Center( @override ), child: Text('Hello, Scaffold!'), Widget build(BuildContext floatingActionButton: FloatingActionButton( context) { onPressed: () { return Scaffold( // Add your onPressed functionality here appBar: AppBar( print('Floating Action Button title: Text('Scaffold pressed'); Example'), }, } child: Icon(Icons.add), ), } ), } ); MOBILE APPLICATION 17 DEVELOPMENT The AppBar widget The AppBar widget in Flutter represents the app bar, a material design component typically used as the topmost element of an application's UI. It often contains the title of the current screen, leading and trailing widgets, and may have additional features like actions, tabs, or navigation controls. MOBILE APPLICATION 18 DEVELOPMENT The AppBar widget class MyApp extends IconButton( StatelessWidget { @overri icon: Icon(Icons.more_vert), de Widget build(BuildContext onPressed: () { context) { return // Add your more options MaterialApp( home: functionality here Scaffold( appBar: print('More options button AppBar( title: Text('AppBar pressed'); Example'), action }, s: [ IconButt ), on( icon: ], Icon(Icons.search onPressed ), ), : () { // Add your search body: Center( functionality here print('Search button child: Text('Hello, AppBar!'), } pressed'); ), , ), ) , ); } MOBILE APPLICATION } 19 DEVELOPMENT Stateless vs. Stateful Widgets Stateless Widgets Stateless widgets are immutable, meaning their properties cannot change once they are created. They do not have any internal state that can change during the lifetime of the widget. Stateless widgets are simple and lightweight, as they do not require managing state. They are primarily used for representing UI components that do not change over time or depend on external factors. Examples of stateless widgets include Text, Icon, Image, FlatButton, etc MOBILE APPLICATION 20 DEVELOPMENT Stateless Widgets class MyTextWidget extends class MyApp extends StatelessWidget { const StatelessWidget { const MyTextWidget({Key? key}) : super(key: MyApp({Key? key}) : super(key: key); @override key); @override Widget build(BuildContext context) { Widget build(BuildContext return const Center( context) { const title = child: Text('Hello'), 'Stateless Widget demo'; ); return MaterialApp( } title: title, } home: } Scaffold( appBar: AppBar( title: const Text(title), ), body: const MOBILE APPLICATION 21 DEVELOPMENT Stateful Widgets Stateful Widgets Stateful widgets, on the other hand, have mutable state, allowing their properties to change over time. They maintain state internally and can be updated based on user interactions, data changes, or other factors. Stateful widgets typically consist of two classes: a StatefulWidget class and a corresponding State class that manages the widget's state. They are used for representing UI components that need to maintain state or respond to user input. Examples of stateful widgets include TextField, Checkbox, Slider, ListView, etc. MOBILE APPLICATION 22 DEVELOPMENT Stateful Widgets class MyApp extends class MyTextWidget extends StatelessWidget { const StatefulWidget { const MyApp({Key? key}) : super(key: MyTextWidget({Key? key}) : super(key: key); @override key); @override Widget build(BuildContext _MyTextWidget createState() => context) { const title = _MyTextWidget(); 'Stateless Widget demo'; } class _MyTextWidget extends return MaterialApp( State { title: title, int count home: = 0; Scaffold( @override appBar: Widget AppBar( build(Build title: const Context Text(title), context) { ), return body: const GestureD child: Center(child: Text('Click Me: MOBILE APPLICATION 2 MyTextWidg DEVELOPMENT 3 Interactivity Widgets This are a graphysical user interface most of the time they must be atractive they have different property MOBILE APPLICATION 24 DEVELOPMENT Drawer Widgets Drawer widget is an interactive widget that allows users to access navigation or additional options by swiping from the edge of the screen or tapping on a menu icon. It's commonly used to provide navigation options in mobile applications, similar to a side menu or navigation drawer. MOBILE APPLICATION 25 DEVELOPMENT ListTile( title: Text('Item 1'), onTap: () { Drawer Widgets // Action when Item 1 is }, tapped ), class MyHomePage extends ListTile( Navigator.pop(context); StatelessWidget { title: Text('Item 2'), @override onTap: () { Widget build(BuildContext context) // Action when Item 2 is { tapped return Scaffold( Navigator.pop(context); appBar: AppBar( }, title: Text('Drawer Example'), ), ), ], drawer: ), Drawer( chi ), ld: ListView( body: Center( padding: child: Text('Hello, Drawer!'), EdgeInsets.zero, ), children: [ ); MOBI}LE DrawerHeader( } APPLICATI child: Text('Drawer ON DEVELOP Header'), decoration: MENT 2 6 Input and Forms: TextField widget class MyApp extends body: Center( child: Padding( StatelessWidget { padding: @override EdgeInsets.all(20.0), child: TextField( Widget build(BuildContext decoration: context) { InputDecoration( labelT return ext: 'Enter your name', border: MaterialApp( h OutlineInputBorder(), ome: Scaffold( ), ), appBar: ), AppBar( ), ), title: ); Text('TextFie } ld Example'), MOBILE APPLICATION } DEVELOPMENT 27 Input and Forms: Checkbox widget class _MyHomePageState extends body: Center( child: State { Checkbox( valu e: _isChecked, bool _isChecked = false; onChanged: (value) @override { setState(() { Widget build(BuildContext _isChecked = context) { value!; }); return Scaffold( }, appBar: AppBar( ), ), title: Text('Checkbox ); Example'), } } ), MOBILE APPLICATION 28 DEVELOPMENT Input and Forms: Radio widget @override mainAxisAlignment: MainAxisAlignment.center, Widget build(BuildContext children: context) { [ Radio ListTile( return Scaffold( title: Text('Option appBar: AppBar( 1'), value: 'Option 1', title: Text('Radio groupValue: Example'), _selectedOption, ), onChanged: (String? value) { setState(() { body: Center( _selectedOption = child: Column( value; }); }, ), MOBILE APPLICATION 29 DEVELOPMENT Input and Forms: Radio widget RadioListTile( RadioListTile( title: Text('Option 3'), title: Text('Option 2'), value: 'Option 3', value: 'Option 2', groupValue: groupValue: _selectedOption, onChanged: (String? _selectedOption, value) { setState(() { onChanged: (String? _selectedOption = value) { setState(() { value; _selectedOption = }); value; }, ), }); ], }, ), ), ), ); } } MOBILE APPLICATION 30 DEVELOPMENT Input and Forms: Button ElevatedButton OutlinedButton TextButton IconButton FloatingActionBu tton MOBILE APPLICATION 31 DEVELOPMENT Button: ElevatedButton body: Center( child: class MyApp extends ElevatedButton( StatelessWidget { onPressed: () { @override // Add your onPressed Widget build(BuildContext functionality here print('Button context) { pressed'); return }, MaterialApp( h child: Text('ElevatedButton'), ome: Scaffold( ), appBar: ), MOBILE APPLICA} TION AppBar( DEVELOPMENT ), title: ); 3 2 Button: OutlinedButton body: Center( child: @override OutlinedButton( child: Widget build(BuildContext Text("Tap on this"), context) { style: OutlinedButton.styleFrom( return primary: Colors.red, Scaffold( ap side: pBar: BorderSide( color: AppBar( Colors.red, title: ), Text("AppMaking.co"), ), centerTitle: true, onPressed: () {}, backgroundColor: } ), MOBILE APPLICATION DEVELOPMENT Colors.blue, ), 3 3 Button: TextButton body: Center( child: class MyApp extends TextButton( StatelessWidget { @override onPressed: () Widget build(BuildContext { context) { return // Add your onPressed MaterialApp( functionality here print('Button home: pressed'); Scaffold( ap }, pBar: child: Text('TextButton'), AppBar( ), title: ), Text('TextBut ), ton ); MOBILE APPLICATION DEVELOPMENT 34 Reading Assignment IconButton Floating Action MOBILE APPLICATION 35 DEVELOPMENT Invisible (Layout and Control) widgets In Flutter, invisible widgets, also known as layout and control widgets, are widgets that are used to manage the layout and behavior of other widgets but are not directly visible on the screen. These widgets help in organizing and controlling the appearance and behavior of visible widgets. MOBILE APPLICATION 36 DEVELOPMENT Invisible (Layout and Control) widgets Container: The Container widget is a versatile widget that can contain other widgets and provides properties for layout, padding, margin, decoration, and more. It's commonly used to create spacing between widgets, apply background colors, or add borders. Row and Column: These widgets are used to arrange child widgets in a horizontal (Row) or vertical (Column) direction. They can contain multiple children and provide properties for controlling alignment, spacing, and flexibility. Stack: The Stack widget is used to overlay multiple widgets on top of each other. Widgets in a Stack are positioned relative to each other or relative to the Stack itself. This is useful for creating complex layouts where widgets need to overlap. ListView: The ListView widget is used to create a scrollable list of children. It's commonly used when you have a large number of children that need to be scrolled vertically or horizontally. MOBILE APPLICATION 37 DEVELOPMENT Invisible (Layout and Control) widgets GridView: Similar to ListView, the GridView widget is used to create a scrollable grid of children. It's useful for displaying items in a grid layout, where each item can have a fixed or flexible size. Spacer: The Spacer widget is used to create flexible space within a Row or Column. It expands to fill the available space along the main axis and can be used to distribute space evenly between widgets. Expanded: The Expanded widget is used to make a child widget expand to fill the available space along the main axis of its parent Row, Column, or Flex widget. It's commonly used in combination with Row or Column to create flexible layouts. Flexible: Similar to Expanded, the Flexible widget is used to make a child widget flexible within its parent's constraints. However, unlike Expanded, it allows the child to grow or shrink based on its flex factor. MOBILE APPLICATION 38 DEVELOPMENT Container the Container widget is a versatile widget used to contain other widgets and provide properties for layout, padding, margin, decoration, and more. MOBILE APPLICATION 39 DEVELOPMENT Container body: Center( child: Container( class MyApp extends width: 200, StatelessWidget { height: 200, color: @override Colors.blue, Widget build(BuildContext child: Center( child: context) { Text( return MaterialApp( 'Hello, Flutter!', home: title: Text('Container Widget ) style: , TextStyle(col Scaffold( Example'), ap ), or: pBar: ), ), Colors.white, }); fontSize: AppBar( } 20), MOBILE APPLICATION ), 40 DEVELOPMENT Row and Column widget the Row and Column widgets are used to arrange child widgets horizontally (Row) or vertically (Column). They are essential for building layouts in Flutter applications. MOBILE APPLICATION 41 DEVELOPMENT Row Widget: The Row widget arranges its children in a horizontal line. It lays out its children along the main axis (horizontal by default) and allows them to occupy the cross-axis (vertical by default) according to their sizes. MOBILE APPLICATION 42 DEVELOPMENT Row Widget: Basic Usage: Row( children: [ Te xt('Hello'), Text('World'), ], ) MOBILE APPLICATION 43 DEVELOPMENT Column Widget: The Column widget arranges its children in a vertical column. It lays out its children along the main axis (vertical by default) and allows them to occupy the cross-axis (horizontal by default) according to their sizes. MOBILE APPLICATION 44 DEVELOPMENT Column Widget: Basic Usage: Column ( childre n: [ Text(' MOBILE APPLICATION DEVELOPMENT 45 Example: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: Container( CrossAxisAlignment.start, width: 100, children: [ height: 100, Text('Hello'), color: Row( Colors.blue, ), mainAxisAlignment: MainAxisAlignment.spaceBetween, ) ], children: [ Text('Flutter'), Text('Widgets'), ], ), MOBILE APPLICATION 46 DEVELOPMENT ListView the ListView widget is used to create a scrollable list of children. It's a commonly used widget when you have a large number of children that need to be scrolled vertically or horizontally. The ListView widget efficiently manages the memory by only loading and displaying the children that are currently visible on the screen. MOBILE APPLICATION 47 DEVELOPMENT Basic Vertical ListView: ListView( children: [ ListTile(ti tle: Text('Item 1')), ListTile(title: Text('Item 2')), ListTile(title: Text('Item 3')), // Add more list items as needed ], ) MOBILE APPLICATION 48 DEVELOPMENT Basic Horizontal ListView: ListView( scrollDirection: Axis.horizontal, children: [ ListTile(title: Text('Item 1')), ListTile(title: Text('Item 2')), ListTile(title: Text('Item 3')), // Add more list items as needed ], MOBILE APPLICATION DEVELOPMENT 49 GridView the GridView widget is used to create a scrollable grid of children. It's similar to the ListView widget but arranges its children in a two-dimensional grid layout, with rows and columns. The GridView widget efficiently manages the memory by only loading and displaying the children that are currently visible on the screen. MOBILE APPLICATION 50 DEVELOPMENT Basic GridView: GridView.count( crossAxisCount: 2, // Number of columns children: [ ListTile(title: Text('Item 1')), ListTile(title: Text('Item 2')), ListTile(title: Text('Item 3')), // Add more grid items as needed ], ) MOBILE APPLICATION 51 DEVELOPMENT Expanded the Expanded widget is used to make a child widget expand to fill the available space along the main axis of its parent widget. It's commonly used within Row, Column, or Flex widgets to distribute available space among their children. MOBILE APPLICATION 52 DEVELOPMENT Basic Usage: Row( children: [ Container(color: Colors.red, width: 50, height: 50), Expanded( child: Container(color: Colors.blue), ), Container(color: Colors.green, width: 50, height: 50), ], ) MOBILE APPLICATION 53 DEVELOPMENT Flexible the Flexible widget is used to make a child widget flexible within its parent's constraints along the main axis. It's similar to the Expanded widget but offers more flexibility in how the available space is distributed among its siblings. MOBILE APPLICATION 54 DEVELOPMENT Basic Usage: Row( children: [ Container(color: Colors.red, width: 50, height: 50), Flexible( flex: 2, child: Container(color: Colors.blue), ), Container(color: Colors.green, width: 50, height: 50), ], ) MOBILE APPLICATION 55 DEVELOPMENT Stack the Stack widget is used to overlay multiple widgets on top of each other. It's commonly used for creating complex layouts where widgets need to overlap or be positioned relative to each other or to the edges of the screen. MOBILE APPLICATION 56 DEVELOPMENT Basic Usage: Stack( Positione d( children: top: 50, [ left: 50, child: Container Container( ( width: width: 100, height: 100, 200, color: height: 200, Colors.red, ) ), color: ), Colors.blue, ], ), MOBILE APPLICATION 57 DEVELOPMENT Spacer the Spacer widget is used to create flexible space within a Row or Column. It expands to fill the available space along the main axis and can be used to distribute space evenly between widgets. MOBILE APPLICATION 58 DEVELOPMENT Basic Usage: Row( children: [ Container(width: 50, height: 50, color: Colors.red), Spacer(), Container(width: 50, height: 50, color: Colors.blue), Spacer(), Container(width: 50, height: 50, color: Colors.green), ], ) MOBILE APPLICATION 59 DEVELOPMENT Documentation : https://api.flutter.dev/flutter/ material/ MOBILE APPLICATION 60 DEVELOPMENT Reading Assignment Refactoring Flutter Widgets MOBILE APPLICATION 61 DEVELOPMENT To be continued on the next Thankslide, you MOBILE APPLICATION 62 DEVELOPMENT