Posts

Showing posts from December, 2021

20. Flutter - Routing (Loading Different Page Widgets)

A route is a map that holds a key (which defines a dart file) and a value (which is a function that loads a widget in the dart file). Defining a route: routes: { "/" : (context) => {WIDGET()}, "/SECONDFILE: (context) = > {WIDGET()}, } // the first route must be empty because it means it is the first widget to display at the start. // requires a context parameter in a route function. Don't need to change. Can override the first route with a property: initialRoute: "/ROUTETOBESTART", Navigating between pages/widgets: Navigator.pushNamed(context, "/ROUTETOGOTO"); // Usage: place this function inside a onPressed function. // pushes a new page onto the current page. // if new page has a appBar, the appBar will automatically have a back button to go back to current page. // Like push and pop.

11. Dart - Maps

 Maps are like structs. Creating a map: Map amap = { "STRING":"HELLO", "string2":"WORLD", "age":25, }; Calling a property of a map: print(amap["STRING"]); // will print "HELLO"

19. Flutter - SafeArea Widget

SafeArea widget prevents widgets from being blocked by the top into bar of a phone (where it shows time and battery, etc) by moving widgets down. Wrap a widget in a SafeArea widget: SafeArea( child: Text('HELLO'), ),

18. Flutter - Widget Classes with Variables and Constructor

 Making a widget a stateless widget that has variables that can be initialized in app. 1. Create a stateless widget. // By stless // OR // Clicking on a widget function and extract it using 2. Create a variable that is "final" final Classname Variablename; // Classname should be the parameter that goes in the widget parenthesis. 3. Create a constructor for the widget class. Class({this.variablename}); 4. Make sure when initializing a widget, put parameter inside the widget parenthesis.

17. Flutter - Card Widgets

Cards are boxes that holds stuff in a fancy design of cards. Card Widget: Card(); Properties: Can use columns/rows/etc. Can use child. Can use margin.

10. Dart - Custom Classes and Importing Dart Files

 Create a custom class inside a separate Dart file: example.dart class Human {     String name = "bob";     int age = 30; }; Importing Dart files into another file: import 'example.dart'; Using Custom Class properties inside flutter: Human personone = Human(); Text('${personone.name}'),

9. Dart - Function Named Parameters

 Named parameters allows us to put parameters in any order as long as the function specified that it uses named parameters. Making a function use named parameters: function( {String name, String job} ){ } // put brackets around the parameters. Using named parameters: function(String: "food cooker", String: "bob")

8. Dart - List Functions

 Defining a List of strings: List<String> Alist = [ "a", "b", "c", ] A List function: Alist.map((letter){ print(letter); }) // this will print every letter in the list. Can transform into arrow function: Alist.map((letter) => print(letter))

16. Flutter - Dynamic Return Widgets from a List

1. Create a List variable. 2. Let flutter automatically create a bunch of Text() widgets using the texts from the List. 3. Column() widget's children's property requires a LIST of widgets. 4. Use a map method on the created List. List<Strings> alist = [ "APPLE", "BANANA", "SPOON", ]; children property will use: children: alist.map((listvalue){ return Text(listvalue); }).toList(), Explaination: (dot)map((){}) // when added to a list, it will go through the list and for every item in the list, it will perform a function using that value, Define the parameter for the value in parenthesis. Define a function in the brackets. (dot).toList() // when added after, it will turn the list of functions into a List that the children property can use.

15. Flutter - Divider Widget

 Divider Widget just places a line separator divider with customizable properties to change its look. Widget: Divider() Properties: height color thickness

14. Flutter - Circle Avatar Widget

Circle Avatar Widget lets you put image assets inside a circle frame border thing. Automatically crops the image to fit inside. Widget: CircleAvatar() Properties: backgroundImage: AssetImage('IMAGEURL') backgroundImage: NetworkImage('IMAGEURL')

13. Flutter - SizedBox Widget

 An empty spacer widget that provides space between widgets. Widget: SizedBox() Properties: height: FLOAT, widgth: FLOAT,

12. Flutter - Expanded Widgets

 Expanded widgets are widgets that expands to take up the whole space the is available. Widget: Expanded() Properties: flex: NUMBER, // ranking of the expanded widget. the higher the number, the more portion of the space they take over other expanded widgets.

11. Flutter - Shortcuts and Tips

Image
Action Menu: Left clicking on a widget will display a lightbulb. Click lightbulb to show actions. Can use to move widget or add things to it. Flutter Outline Menu: Right side of Android Studio. It is a tab and does similar stuff like Action Menu when Right Clicking a Widget. It summarizes and shows the widget in a tree-like structure. Left clicking will go to that widget.

10. Flutter - Rows / Columns

 A row is a widget that holds other widgets horizontally. A column is a widget that holds other widgets vertically. Both can hold multiple widget childs, but cant use child, use children property instead. mainAxis vs crossAxis: - mainAxis is the main axis of column or row. If row, it is horizontal, else if column it is vertical. - crossAxis is the secondary axis of column or row. If row, it is vertical, else if column it is horizontal. Row Widget: Row() Row Properties: children: <Widget>[WIDGET,WIDGET] // a array of widgets mainAxisAlignment: MainAlignmentAxis.ALIGNMENTMETHOD // aligns widgets horizontally crossAxisAlignment: CrossAlignmentAxis.ALIGNMENTMETHOD // aligns widgets vertically Column Widget: Column() Column Properties: children: <Widget>[WIDGET,WIDGET] // a array of widgets mainAxisAlignment: MainAlignmentAxis.ALIGNMENTMETHOD // aligns widgets vertically crossAxisAlignment: CrossAlignmentAxis.ALIGNMENTMETHOD // aligns widgets horizontally

9. Flutter - Layouts/Containers/Padding/Margins

Containers/Layouts usually go into a "body: " property. Container Widgets: Container() Container Properties: padding // used to specify paddings margin // used to specify margin color child Margin vs Padding: - margin is for the outside of the container - padding is for the inside of the container Padding Property: padding: EdgeInsets.PADDINGMETHODNAME PADDINGMETHODNAMES: All(float) // equal padding on all sides. symmetric(horizontal: float, vertical: float) // equal padding on two parameter mirrors fromLTRB(float,float,float,float) // left, top, right, bottom separate values for padding Padding Widget (for individual widgets like a text widget. use in-place of a container): Padding( padding: EdgeInsets.all(50.0) child: Text("HELLO") ) Margin Property: margin: EdgeInsets.MARGINMETHODNAME MARGINMETHODNAMES: All(float) // equal margin on all sides. symmetric(horizontal: float, vertical: float) // equal margin on two parameter mirrors fromLTRB(float,float,float,float)

8. Flutter - Buttons & Icons

Icons widget: Icon() // widget Icons.ICONNAME // property of Icon() widget. Replace ICONNAME with icon // get icons from https://api.flutter.dev/flutter/material/Icons-class.html Icons common properties: Icons.ICONNAME color size Icons example: body: Center ( child: Icon ( Icons. airport_shuttle , color: Colors. lightBlue , size: 50 , ) , ) , Button Widget Types: - RaisedButton() // has shadow - FlatButton() // has no shadow Button Common Properties: onPressed: () {} // required property. A function when button is pressed. child: Text() color: Colors.COLORNAME Text Buttons with Icons (separate widgets from button widget): - RaisedButton.icon() - FlatButton.icon() // requires " onPressed: () {} " property // change icon with " icon: Icons() " property and widget // change the text associated with the icon with " label: Text('TEXT') " property and widget Example Button+Icon Combo: body: Center ( child: FlatButton . icon (

7. Flutter - Images & Assets

Image Widget: Image() // widget image: // property of the image widget Network Images (Using images on internet): Image( image: NetworkImage('IMAGEURL'), ) Asset Images (Using images on the project source folders): 1. Create a new image folder in project. Maybe call it "assets" 2. Add images 3. Edit pubspec.yaml file to use source images. Find assets section. assets : - assets/doge1.png - assets/doge2.png - assets/doge3.png // If have too much images. Just reference the "assets" folder by itself only. Then any image inside it can be used. Image( image: AssetImage('assets/doge1.png'), ) Example of Image Widget being used: body: Center ( child: Image ( image: AssetImage ( 'assets/doge2.png' ) , ) , ) , Shortcuts to asset/network images: Image.asset('URL') Image.network('URL')

6. Flutter - Stateful Widgets

 Stateful widgets automatically refreshes whenever data of variables inside its object widget is changed. 1. Create a stateful widget using snippet shortcut "stful" 2. It will create two classes. class TESTWIDGET extends StatefulWidget { const TESTWIDGET({Key? key}) : super (key: key) ; @override _TESTWIDGETState createState () => _TESTWIDGETState () ; } class _TESTWIDGETState extends State<TESTWIDGET> { @override Widget build (BuildContext context) { return Container () ; } } TESTWIDGET // is the initializer widget which creates a state object widget called _TESTWIDGETState. _TESTWIDGETState // works like a stateless widget but can put variables above @override. Change Container() to widget root that you want to use. Can use Action Menu to quickly convert a stateless widget into a stateful widget. Changing variables in a stateful widget: Use function setState( (){} ) // Inside brackets is a function. setState is a function holding a function. Change

5. Flutter - Stateless Widget Class (&HotReloads)

Stateless vs Stateful Widget: - Stateless: state of widget cannot change over time. Final Widget. - Stateful: state of widget can change over time. Dynamic Widget. - Stateful and Stateless widget are basically custom widgets. We can put any widget inside it by returning a widget. Creating a stateless widget class: Using snippet "stless" class testclass extends StatelessWidget { // const test({Key? key}) : super (key: key) ; @override Widget build (BuildContext context) { return Container () ; } } // Replace Container() with widget tree widget, for example, the Scaffold() Widget. // The "@override" tells the function to override the extended "StatelessWidget's" own build function with the one in our custom stateless widget. // Stateless widget is basically a widget. If we pop it as a widget in the "home: " property of the app, then it becomes the home widget. // Any change within the build function will be updated on a save (hot re

4. Flutter - Custom Fonts

1. Create new "fonts" folder in flutter project. 2. Add font file to the folder 3. Edit "pubspec.yaml"  4. Uncomment Font Section 5. Name a new family 6. Change the asset to reflect the font file. fontFamily: 'FAMILY1', // to use this font in a text widget in the fontFamily property. // CTRL+WINDOWS+/ to uncomment // Tab  to indent // Shift+Tab to unindent # - family: Schyler # fonts: # - asset: fonts/Schyler-Regular.ttf # - asset: fonts/Schyler-Italic.ttf # style: italic # - family: Trajan Pro # fonts: # - asset: fonts/TrajanPro.ttf # - asset: fonts/TrajanPro_Bold.ttf # weight: 700 # fonts : - family : FAMILY1 fonts : - asset : fonts/IndieFlower-Regular.ttf

3. Flutter - Text Widget

  Text Widget: child: Text() Expanded Text Widget : Text( "HELLO", style: TextStyle(), // TextStyle Widget ) TextStyle Widget Properties: fontSize: 50.0, fontWeight: FontWeight.bold, letterSpacing: 2.0, color: Colors.grey[600], fontFamily: 'FAMILY1',

2. Flutter - Widgets and Properties

All widgets must be defined by a property. All widgets have a list of property that can be changed. Sometimes their value can be regular bool/ints/floats/etc but can also be other widgets (when being containers). Common properties: home // property of the app. defines the root widget to show at the start. body // property of the scaffold widget. used to hold widgets. child // property used inside another widget to include child widgets backgroundColor // lets use material design colors. Common widgets: AppBar() //  Center() // put child property inside Text() // shows text FloatingActionButton(onPressed:(){}, child: WIDGETHERE,) Colors // colors. CTRL+Q will let use shade of color.

1. Flutter - App Basics

Everything in a flutter app is a widget. Everything is a widget within a widget. The root widget is the core and expanding under it are everything else just like a tree. A widget tree. Widgets always need properties to define them. Creating Project 1. Create a folder 2. Open CMD 3. "flutter create projectname" project names with spaces are typed with _ no dashes or whitespace Ex: Project_Name Hot Reload with VSCODE. 1. Open CMD in a flutter project. 2. flutter run 3. Controls: r = hot reload shift+r = full reload ctrl+c = quit App needs to run by initialing a root widget in main: void main() => runApp(ROOTWIDGETNAMEHERE); // can put any widget between parenthesis. Basic Start of an App using MaterialApp() widget as the root: void main() => runApp(const MaterialApp(   home: Text("HELLO"), )); // home property will have a text widget. specifies what will be on home screen when app loads. App using a scaffold (basic starter root widget): void main() =

8. Dart - Inheritance Classes

 Make a default class: class User {     String username;     int age;     void printmyinfo() {          print('$username is $age years old');      }     User(this.username, this.age); // constructor } Make a inheritance class (inherits all stuff from class above but has extra stuff): // need to create a super constructor if the extension target class has a constructor class UserBoss extends User {     UserBoss(String a, int b) : super(a,b); // must be same as the variable declared in UserBoss     // "super" is a constructor that changes the extension target classes' property     // aand bare property variable of the UserBoss class and similar for User class     void printbossstuff() {          print('boss stuff');      } }

7. Dart - Classes (Like Structs in Golang)

Defining a class: class User {     String username = "todd";     int age = 30;     void printmyinfo() {          print('$username is $age years old');      } } Defining a variable as the class: User person = User(); Calling class property: print(person.username); or print('${person.username}') Calling class method: person.printmyinfo(); Changing property of class: person.username = "mary"; Defining a class with a constructor (which edits property of the class when initiating with a value): class User {     String username;     int age;     void printmyinfo() {         print('$username is $age years old');     }     User(this.username, this.age);     // this is a constructor for the variables inside this class } Defining a variable as the class with constructor parameters: User person = User("amy",50);

6. Dart - Lists (Arrays)

Defining a list: List alistname = ['bob', 'todd', 'dad']; print(alistname); print(alistname[0]); // indexing Defining a specific list type: List<String> alistname = ['bob', 'todd', 'dad']; List<int> alistage = [30,50,60]; // use arrow brackets to define types. Editing a list with built-in methods: alistname.add("mary"); alistname.remove("todd"); // if a list is not defined to a specific type, then you can add any type to it.

16. Go - Linked Lists

 package main import "fmt" type node struct { // nodes data int next *node } type linkedList struct { // linked list head   *node length int } func (l *linkedList) prepend(n *node) { // method second := l.head l.head = n l.head.next = second l.length++ } func main() { mylist := linkedList{} node1 := &node{data: 50} node2 := &node{data: 60} node3 := &node{data: 70} mylist.prepend(node1) mylist.prepend(node2) mylist.prepend(node3) fmt.Println(mylist) fmt.Println(mylist.head.next.next.data) }

15. Go - Structs

Struct is an aggregate data type that aggregates together values of different types. Creating struct: type myStruct struct {     name string     age int } Creating a variable using a type struct: // Using composite literal TYPE{values} to create.     personA := myStruct {         name: "BOB" ,         age: 32 ,     } Accessing fields in a struct: // Using dot notation     fmt. Println (personA.age,personA.name) Sample Code: package main import "fmt" // Human Struct type humanA struct {     gender string     age     int     weight float64 } // func (a *humanA) printdetail () {     fmt. Printf ( "Name: Peter \n Gender: %s \n Age: %d \n Weight: %g " , a.gender, a.age, a.weight) } func main () {     var peter = new (humanA)     * peter = humanA{ "Male" , 30 , 50.00 }     peter. printdetail () } Creating anonymous structs: // Initializing a struct in a variable and declaring its values at the same time. Used for one time declaration.    

14. Go - Methods and Pointers

Methods allow type structs defined in the func's receiver to access the func's stuff. Code Examples: package main import "fmt" type human struct { // struct     gender string     age int     weight float64 } /*func (a *human) printdetails() { // method     fmt.Printf("Name: Peter\nGender: %s\nAge: %d\nWeight: %g", a.gender, a.age, a.weight) }*/ func printdetails (a *human) { // non method     fmt. Printf ( "Name: Peter \n Gender: %s \n Age: %d \n Weight: %g " , a.gender, a.age, a.weight) } func main () {     var peter = new (human)     * peter = human{ "Male" , 30 , 50.00 }     //peter.printdetails() // Method     printdetails (peter) // Non method } // methods are functions of a struct/class // can take a pointer receiver for the struct or a value receiver.

13. Go - Modules/Libaries/Packages

 go mod init MODULE_NAME go get LIBARY_NAME_ON_GITHUB // use both in same folder of project go mod tidy  // downloads required dependencies in a project go mod tidy -v // updates the dependencies in go.mod and go.sum files to match what is currently used in project

12. Go - RNG

 import "math/rand" rand.Seed(time.Now().UnixNano()) variable := rand.intn(50) // RNG from 0 to 50 rand.Float64() // RNG from 0 to 1.0 rand.Intn(max-min) + min // RNG from min to max rand.Perm(100) // RNG shuffled array from 0 to 100

11. Go - Input Bufio

BUFIO METHOD import "bufio" import "os" scanner := bufio.NewScanner(os.Stdin) scanner.Scan() variable := scanner.Text() fmt.Println(variable) FMT METHOD var name string var age int fmt.Scanln(&name, &age) fmt.println(name,age) // this method doesnt count white spaces Increasing line buffer read size limit: const maxCapacity = 512 * 1024 // max capacity buf := make([]byte, maxCapacity) // buffer scanner.Buffer(buf, maxCapacity) // put before scanning

10. Go - Maps

Maps are key-value store. It's an un-ordered list. Maps are a reference type meaning it will pass a reference of its values instead of a copy. Creating maps: var VARIABLE = map[KEY_TYPE]VALUE_TYPE{KEY_VALUE:VALUE_TYPE} var map1 = map[string]int{} var variable = make(map[string]int) Getting value from map: variable["KEY1"] = 50 variable2["KEY1"] = "KEY2" Getting value and return whether found: package main import "fmt" func main () {     var map1 = map [ string ] int { "TEST" : 3 }     v , ok := map1[ "TEST" ]     fmt. Println (v, ok) } Getting value existence and acting upon true: package main import "fmt" func main () {     var map1 = map [ string ] int { "TEST" : 3 }     if v , ok := map1[ "TEST" ]; ok {         fmt. Println (v)         fmt. Println ( "exists" )     } } Deleting key-value from map: delete(mapvarable,KEY) Iterating map: package main import "fmt&q

9. Go - IF/THEN and Switches

IF/ELSE IF/ELSE: package main func main () {     x := 4     if x == 5 {     } else if x == 6 {     } else {     } } Switches: // putting value expression in front of switch for cases to check. if empty, run bool as true by default package main import "fmt" func main () {     switch {     case 5 == 5 :         fmt. Println ( "one" )     case true :         fmt. Println ( "two" )     } } // can include multiple variablevalue checks by separation of a comma     case 5 == 5 , 2 == 5 :         fmt. Println ( "one" ) // include fallthrough to enable the check and not break the switch. fallthrough also makes case after it run even if false. (one fallthrough valid for one case. multiple fallthroughs needed to fall through entire switch statement) package main import "fmt" func main () {     switch {     case 5 == 5 , 2 == 5 :         fmt. Println ( "one" )         fallthrough     case false:          fmt.Prin

8. Go - Loops

For Loop with For Clause Format: for INIT; CONDITION; POST {ACTION}  // can omit INIT if using an already declared variable. Single Loop: for i:=1,i<10,i++ {     loop, and increment up to 10 } Nested Loops: for i:=1,i<10,i++ {     for i:=1,i<10,i++ {     loop, and increment up to 10 } } Infinite Loop: for {} For Loop with Single Conditional Statement: for x == 5 {     loop } i := 5 for i <=10 {     loop } for a,b := range arrayvariable{     fmt.println(a) // prints index     fmt.println(b) // prints index's value } break // break loops continue // voids block below but continue on with loop example: for i < 5{ i++ if  i == 4{ continue } fmt.Println(i) }

7. Go - Variable Declaration

Variable Declarations: Declare variable types using "var" // Single Variable Declaration var age int var names string var width float64 // Pointers Variables var agePointer * int var namesPointer * string var widthPointer * float64 Struct Declaration and Use:     type Person struct {         gender string         age int     }         todd := Person{         gender: "male" ,         age: 5 ,     }     fmt. Println (todd.gender) Declaring multiple variables: var (     age = 5     names = "todd"     baldQuestion = false ) Constants, variables that cannot be changed. They're immutable. // Declaring single constants const age int const name string // Declaring multiple constants const (     a = 5     b = 6     c = "string" ) Short Declaration Operator uses the " := " symbol.  Lets declare stuff without typing var.  Can only use within a function's scope, can't be used outside of a function. Declare vari

6. Go - Logical Operators Basics

Operators: && // AND || // OR ! // NOT == // EQUAL >= <= > < % // Modulus %, for remainders Operators vs Operands: - Operators are the symbols that compare logic. - Operands are the objects being compared by the operators.

5. Go - Build and Run

 go build gofile.go // builts a executable go run gofile.go // runs go code go build -ldflags "-X main.variable=value -H=windowsgui" // -X : changes a variable in the code // main.variable = value go build -ldflags "-H=windowsgui" // hides CMD prompt when building/running app go build -ldflags "-H=windowsgui -s -w" // hide CMD prompt and shrinks exe file size go build -ldflags "-X main.variable=value -Xmain.variable2=value2" // change two variables

4. Go Array Basics

Arrays are a data structure with a fixed size and type. Creating arrays: var VARIABLE_NAME = [INT]TYPE{} var bag = [ 10 ] string {} Sample: package main import "fmt" type tables struct {     name string     age int64     cash int64 } var arrays = [ 5 ]tables{} var intarray = [ 5 ] int {} var stringarray = [ 5 ] string {} // var variable [indexlimit]type{values} // var variable [...]type{values} func main () {     arrays[ 0 ] = tables{ "bob" , 64 , 300 }     fmt. Println (array[ 0 ].age) }

3. Go - Pointer Basics

Pointer is a reference to a memory, or an address to something saved in memory.  Could use pointers to reference big data stored in memory to save time and efficiency. Could also use pointers to change values outside of scopes. Example Code: // creating a variable that returns a pointer package main import "fmt" var pointervar * int // This is a pointer type with int func main () {     variable := "string"     intvar := 50     pointervar = &intvar     var x int = MathAdd (&variable)     fmt. Println (variable)     fmt. Println (x)     fmt. Println (*pointervar) } func MathAdd (p * string ) int {     * p = "toy"     return 5 } * = pointer to a type/variable, the value that is stored at address & = address of a type/variable where its stored *& = dereference the value stored at the address var b = new(int) // this creates a variable integer that also returns a pointer. can reference pointer b with "&b" Dereferenc

2. Go - Basic Format Printing

Example Code: package main import "fmt" func test (a int , b string , c bool , d float64 ) ( int , string , bool , float64 ) {     x := a + 5     y := "world"     z := true     x1 := 5.06     return x, y, z, x1 } func main () {         xstring := "STRING"         fmt. Println ( len (xstring))         fmt. Println (xstring[ 0 ])         fmt. Println (xstring+ "VALUE" )     answer , a , b , c := test ( 50 , "hello" , false , 3.2 )     fmt. Printf ( "Number: %d , String: %s , Bool: %t , Float: %g " , answer, a, b, c) } Strings can be declared with double quotes: var name = "hello" Strings can be declared with back quotes: Everything between the backquotes will be a string. Don't have to use escapes, they print as is. var name = `"hello" world` Types of Printing: Print Group: Printing to stdout (standard output) Print() // prints without a newline Println() // prints and adds a newline Printf

1. Go - Basics

https://gobyexample.com // has a lot of tutorials Statements are single line instructions. Expressions are like "2+2". Statement example: fmt.Println(2+2) - Whole line is a statement, 2+2 is the expression. Can declare multiple statements on a single line by separating them with a semi-colon.     fmt. Println ( "TOOD" ) ; fmt. Println ( "DAD" ) Example Code: package main import "fmt" func functionB (a int ) int {     temp := a * 5     return temp } func functionA () {     fmt. Println ( "world" ) } func deferredfunction () { } func main () {     defer deferredfunction ()     var test string     test = "hello"     fmt. Println (test)     functionA ()     test2 := functionB ( 5 )     fmt. Println (test2)     banana := 50.50     fmt. Println (banana) }