Last active
July 14, 2021 14:59
-
-
Save byJeevan/cbf85eb8e3965955c40bb532b67f5bdf to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-------------------------------------------------- | |
##Flutter Notes | |
from byjeevan.blogspot.com | |
-------------------------------------------------- | |
Course Res: https://github.com/londonappbrewery/Flutter-Course-Resources | |
Flutter Cheetsheet : https://medium.com/flutter-community/flutter-layout-cheat-sheet-5363348d037e | |
Dark Cheetsheet : https://dart.dev/codelabs/dart-cheatsheet | |
🎯 Dart is Object Oriented Programming languages. | |
Few frequently used Widgets : | |
********************************************************** | |
🚀BoxDecoration widget -for- Background Image for Container | |
choose AssetImage for Local or NetworkImage for remote. | |
🚀'Visibility' widget usefull Hide and show buttons (ex. FlatButton) | |
🚀 'IconButton' widget helps to add simple AppBar Actions | |
🚀 'SingleChildScrollView' with scrollDirections helps Row / Columns to make scrollable. | |
🚀 'SizedBox(height: <eg. 20>)' gives space b/w Column childs | |
🚀 Flat button comes with full set pack of | |
icon + text + action syntax: FlatButton.icon(onPressed: null, icon: null, label: null) | |
*************** Dart documentaiton notes ************* 17/04/2020 | |
1. | |
Method return type if you not specify, then it will 'dynamic' type. | |
void main() { | |
print('hello ${returnsTest(1)}'); | |
} | |
//below method can return int or string type. | |
returnsTest(int flag) { | |
if (flag == 1) { | |
return 1; | |
} | |
return "na"; | |
} | |
2.Important concepts | |
Everything you can place in a variable is an object, and every object is an instance of a class. Even numbers, functions, and null are objects. All objects inherit from the Object class. | |
Although Dart is strongly typed, type annotations are optional because Dart can infer types. In the code above, number is inferred to be of type int. When you want to explicitly say that no type is expected, use the special type dynamic. | |
Dart supports generic types, like List<int> (a list of integers) or List<dynamic> (a list of objects of any type). | |
Dart supports top-level functions (such as main()), as well as functions tied to a class or object (static and instance methods, respectively). You can also create functions within functions (nested or local functions). | |
Similarly, Dart supports top-level variables, as well as variables tied to a class or object (static and instance variables). Instance variables are sometimes known as fields or properties. | |
Unlike Java, Dart doesn’t have the keywords public, protected, and private. If an identifier starts with an underscore (_), it’s private to its library. For details, see Libraries and visibility. | |
Identifiers can start with a letter or underscore (_), followed by any combination of those characters plus digits. | |
Dart has both expressions (which have runtime values) and statements (which don’t). For example, the conditional expression condition ? expr1 : expr2 has a value of expr1 or expr2. Compare that to an if-else statement, which has no value. A statement often contains one or more expressions, but an expression can’t directly contain a statement. | |
3. Function as parameter | |
void main() { | |
helloOne(hello); | |
} | |
void hello() { | |
print("Hello World"); | |
} | |
void helloOne(Function hello) { | |
hello(); | |
} | |
4. | |
//'final' are Run-Time constant | |
final List list = [1, 2, 3]; | |
list[2] = 4; //okey. Prints [1, 2, 4] | |
print(list); | |
//'const' are Compile-Time constant | |
const List list = [1, 2, 3]; | |
list[2] = 4; // error : Uncaught Error: Unsupported operation: indexed set | |
print(list); | |
5. List | |
Array - Ordered collection of same object. | |
We can use the spread operator (...) to insert all the elements of a list into another list | |
List<String> brands = ['BMW', 'Tesla', 'TATA'] | |
To Add : | |
brands.add('Honda') | |
To find index: | |
brands.indexOf('Tesla') //gives 1 | |
To insert item : | |
brands.insert(2,'TOYOTA') //gives ['BMW', 'Tesla', 'TOYOTA', 'TATA' , 'Honda'] | |
6. Set | |
A set in Dart is an unordered collection of unique items. | |
Set setOfUnique = {"one", "two", "three", "three", "four"}; | |
print(setOfUnique); | |
7.Map | |
A map is an object that associates keys and values. Both keys and values can be any type of object. Each key occurs only once, but you can use the same value multiple times | |
Map map = new Map(); | |
Map m = {"ID": "1234", "Name": "Sumit"}; | |
example : void main() { | |
List l = ["one", "two", "three"]; | |
Map map = new Map(); | |
map["hello"] = "world"; | |
map["list"] = l; | |
print(map); | |
} | |
9.Symbols | |
A Symbol object represents an operator or identifier declared in a Dart program. You might never need to use symbols, but they’re invaluable for APIs that refer to identifiers by name, because minification changes identifier names but not identifier symbols. | |
To get the symbol for an identifier, use a symbol literal, which is just # followed by the identifier: | |
#radix | |
#bar | |
Symbol literals are compile-time constants. | |
10.Functions | |
=> expr syntax (Arrow sytanx) is a shorthand for { return expr; } | |
Example for Arrowed function: | |
int add() => 5 + 2; | |
is same as - | |
int add() { | |
return 5 + 2; | |
} | |
Optional parameters are mentioned inside {} | |
Tip: Optional parameters can be either named or positional, but not both. | |
11. | |
Named parameters: | |
Positional parameters: | |
Required parameters: | |
Default parameter values: | |
Your function can use = to define default values for both named and positional parameters. | |
/// Sets the [bold] and [hidden] flags ... | |
void enableFlags({bool bold = false, bool hidden = false}) {...} | |
// bold will be true; hidden will be false. | |
enableFlags(bold: true); | |
12. Exceptions : | |
try { | |
breedMoreLlamas(); | |
} on OutOfLlamasException { | |
// A specific exception | |
buyMoreLlamas(); | |
} on Exception catch (e) { | |
// Anything else that is an exception | |
print('Unknown exception: $e'); | |
} catch (e) { | |
// No specified type, handles all | |
print('Something really unknown: $e'); | |
} | |
finally { | |
// Always clean up, even if an exception is thrown. | |
cleanLlamaStalls(); | |
} | |
13. | |
Callable classes | |
To allow an instance of your Dart class to be called like a function, implement the call() method. | |
class WannabeFunction { | |
String call(String a, String b, String c) => '$a $b $c!'; | |
} | |
var wf = WannabeFunction(); | |
var out = wf('Hi', 'there,', 'gang'); | |
main() => print(out); | |
--------- FLUTTER SDK ------- | |
1. Minimal app code with 2 widgets tree as : | |
(Material App Widget ---- > Text Widget) | |
void main() { | |
runApp(MaterialApp(home: Text("Hello World!"),),); | |
} | |
2. Use single ' for dart strings | |
Image widgets can be dartui or flutter widget. | |
*** ShortCuts ***** | |
Hit [option]+ [Enter] to embed widgets options | |
hit [Control] + [j] to get Documentation dialog over any widget. | |
To create stateless widget :- | |
type 'stless' and hit enter. | |
****** Widgets ***** | |
- Single Child Widget : | |
Container, Center, SafeArea, Card (ps: add Padding widget), | |
Expanded (placed above Column to fillup space) | |
- Multi Child widget | |
Row, Column, Stack | |
OOPS ! | |
Encapsulation Private accessors | |
_ before object makes private variable | |
class Car { | |
int _bhpOfCar = 200; //Private to car class | |
void drive(){ | |
print('Turn wheels'); | |
} | |
} | |
Inheritance: | |
class ElectricCard extends Car { | |
//gets all properites & methods from Car class. | |
} | |
Polymorphisms: | |
class LevitatingCar extends Car { | |
@override | |
void drive(){ | |
print('glide towards'); | |
} | |
} | |
Constructors: | |
class Human { | |
double height; | |
//custom contructor | |
Human({double startingHeight}) { | |
height = startingHeight; | |
} | |
//-or- | |
Human({double height}) { | |
this.height = height; | |
} | |
//same as above constructor - non named parameters | |
Human({this.height}); | |
//Human() {} //Dart given default constructor | |
} | |
/**** Defining Global Constants ***/ | |
// Contants.dart file | |
library constants; | |
//Strings | |
const String ERROR_MSG = 'Oops! Failed to add todo'; | |
//Colors | |
const Color themeDarkColor = Color(0xff162447); // 0xff + 162447 | |
const Color themeLightColor = Color(0xff1f4068); | |
const Color themePallet1Color = Color(0xff1b1b2f); | |
const Color themePallet2Color = Color(0xffe43f5a); | |
//Usage | |
import 'constants.dart' as Constants; | |
eg : color:themeDarkColor | |
eg : Text(ERROR_MSG) | |
******* |
API Level 19 (Kitkat) support
In /android/app/src/main/kotlin/MainActivity.kt
package com.jda.preinterview.flutter_app_base
import androidx.annotation.NonNull;
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugins.GeneratedPluginRegistrant
import android.os.Build //1. import
class MainActivity: FlutterActivity() {
override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
GeneratedPluginRegistrant.registerWith(flutterEngine);
}
//2. override onFlutterUiDisplayed
override fun onFlutterUiDisplayed() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
reportFullyDrawn();
}
}
}
UITableview Alternative:
SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Text("This widget is useful when you have a single box that will normally be entirely visible, for example a clock face in a time picker, but you need to make sure it can be scrolled if the container gets too small in one axis "),
Container(color: const Color(0xffeeee00),
height: 120.0,
alignment: Alignment.center,
child: const Text('Fixed Height Content'),
),
Container(color: Colors.blue,
height: 120.0,
alignment: Alignment.center,
child: const Text('Fixed Height Content'),
),
Text("Ends intrinsic size"),
Container(color: const Color(0xffeeee00),
height: 120.0,
alignment: Alignment.center,
child: const Text('Fixed Height Content'),
)
],
),
),
Also we can add inner level of Column
as child to the Container
. Child can grow based on the text size (intrinsic).
Container(color: secondaryBlue,
alignment: Alignment.center,
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Container(color: Colors.black12,
alignment: Alignment.center,
child: const Text('Variable Height based on the length of the text given in this container. Repeating - Variable Height based on the length of the text given in this container.'),
),
Container(color: Colors.green,
height: 120.0,
alignment: Alignment.center,
child: const Text('Fixed Height Content'),
)]),
),
Container
1. Decoration for Container - Rounded Border & Shadow
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.all(Radius.circular(10.0)),
boxShadow: [BoxShadow(color: Colors.black26, blurRadius: 8.2)]
),
2.
Padding and Margin can be added to Container
Container(
padding: const EdgeInsets.all(16.0),
margin: const EdgeInsets.all(16.0),
.... )
3. Click event for Container say with Rows/Column
InkWell(
child: Container(......),
onTap: () {
print("Click event on Container");
},
);
4. Linear gradient color
decoration: BoxDecoration(
gradient: const LinearGradient(
colors: [Color(0xFFD4418E), Color(0xFF0652C5)],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
),
The Flexible does the trick - multiple line text wrap
new Container(
child: Row(
children: <Widget>[
Flexible(
child: new Text("A looooooooooooooooooong text"))
],
));
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The Boring Show - The official Flutter Developer Youtube series created by the Google Flutter team.
Build Native Mobile Apps with Flutter - This is a free Udacity course created by the Google Flutter team.
Flutter Docs - While I can't recommend most docs as a learning resource, I would make an exception for the Flutter Docs. They are really great not just as a reference but as a study aid. I especially recommend the Codelabs.
It's All Widgets - Published apps made with Flutter
Flutter Widget Livebook - A live, animated reference of Flutter Widges
Flutter Gitter - The Flutter Community in Gitter chat.
Flutter Events - Find a mentor, get in touch with your local Flutter community and learn new things you can do with Flutter by going to a Flutter event near you.