Flutter & Dart Flashcards

1
Q

What is Flutter?

A

Open-source framework (tools, libraries, and conventions) developed by Google that supports building natively compiled, cross-platform(iOS, Android, MacOS, Linus, Windows, Web) applications from a single codebase.

Flutter uses Google’s Dart OOP language and provides a rich set of widgets for (and libraries???) for building beautiful and interactive user interfaces (UIs).

First released in December 2018.

Virtual Machine allows Hot Restart and Hot Reload - see changes without needing to restart the app - efficient development.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is Dart?

A

Google’s open-source, OOP language released in 2011 with a strong, C-style syntax.

Is a statically-typed language - variable and function types are checked at compile-time instead of runtime.

Supports asynchronous programming with async, await, Futures, and Streams.

Has Dart DevTools for debugging and performance analysis.

Has several core libraries such as dart:io, dart:math, dart:convert.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Text Editor vs. Compiler vs. Software Development Kit

A

Text Editor: software tool for creating, editing, and manipulating text files, provides functionality for typing and formatting text. May include syntax highlighting, search and replace, and file management.

Compiler: software tool that translates source code into machine code or executable code that can be directly executed by a computer’s processor. It takes the source code, analyzes for syntax and semantic errors, and generates compiled code, which is usually stored in a separate file.

SDK: collection of software tools, libraries, documentation, and sample code to assist developers in creating software applications for a specific platform, framework, or programming language. Includes development tools, such as compilers and debuggers, libraries and APIs that provide pre-written code for common tasks.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Graphical User Interface vs. Command Line Interface

A

GUI: visual interface for users to interact with a computer system or software application using graphical elements such as icons, buttons, windows, and menus. Users can interact with the system or application by using a mouse, keyboard, or touch input.

CLI: text-based interface that allows users to interact with a computer system or software application by entering text-based commands or instructions. Users type commands, often with parameters or options, at a command prompt, and the system or application responds with text-based output.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Object Oriented Programming Core Concepts

A

Classes and Objects: Classes are blueprints or templates for objects, and objects are instances of classes. Classes define the structure and behavior of objects, while objects are specific instances created from those classes.

Encapsulation: Encapsulation is the process of hiding the internal details of an object and exposing only what is necessary. It involves using access modifiers (such as public, private, and protected) to control the visibility and accessibility of class members (i.e., variables and methods).

Inheritance: Inheritance allows one class (the child or subclass) to inherit properties and methods from another class (the parent or superclass). It promotes code reuse and allows for the creation of hierarchical relationships between classes.

Polymorphism: Polymorphism enables objects of different classes to be treated as if they were of the same class, providing a consistent interface for interacting with objects. It allows for method overriding, interfaces, and abstract classes.

Abstraction: Abstraction involves simplifying complex systems by creating abstract classes or interfaces that define common properties and behaviors, without providing implementation details. It allows for creating reusable and extensible code.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Dart Project Files

A

.gitignore: informs Git on which files it should NOT save to GitHub or other remote repository.

analysis_options.yaml: contains rules to help detect issues with code (aka: linting).

bin: the executable Dart code.

CHANGELOG.md: Markdown formatted list of updates to the project.
lib: short for “library,” contains all the .dart files (aka: “collection”).

pubspec.yaml: list of third-party packages for the project.

pubspec.lock: specifies precise versions of each package (aka: dependency) in the pubspec.yaml file.

README.md: place to describe the project and how to use it.

test: stores test files.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is a Widget?

A

Basic building blocks of the UI (user interface) that describe the layout, appearance, and behavior of a certain part of the UI.

Is a class that represents a visual element, such as a button, text box, image, or container, which can be combined with other widgets to create a complete user interface.

Are organized in a tree-like structure, known as the widget tree or widget hierarchy, where parent widgets can contain child widgets, forming a parent-child relationship.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Two Fundamental Widgets

A

Stateless Widget: represents part of the UI that does not store any mutable (AKA: changeable) state. Is only rebuilt when a parent widget is rebuilt. Typically used for parts of the UI that do not need to change dynamically (continually able to change), such

Displaying static text, images, or icons…

Stateful Widget: a widget that can hold mutable state, meaning it can change its internal data over time. Used to create components in a Flutter application that need to maintain and update their internal state.

When created, it also creates a separate State Object that holds the mutable state. When the state changes, the framework rebuilds the widget.

For example, user input forms, animations, or data that changes dynamically…

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Stateful Widget Lifecycle

A
  1. createState( ): creates the state object of a Stateful Widget, is where the mutable (changeable) state (information) is stored
    * mounted (true): once called, the framework will associate the BuildContext (aka: insert into the widget tree)
    to the Stateful widget by setting the mounted property as true
  2. initState( ): called only once when the widget’s state object is created, best for http requests, subscribing to streams, or any object that could change the data of this widget.
  3. didChangeDependencies( ): called right after initState( ) or when an object that this widget depends on changes.
  4. build( ): required and will be called many times during the widget’s lifecycle.
  5. didUpdateWidget( ): called if the parent widget changes its configuration and has to rebuild the widget, framework gives you the old widget as an argument that you can use to compare it with the new widget, Flutter will call the build() method after it.
  6. setState( ): notifies the framework that the state of the object has changed (aka: “dirty”), the framework will then run the build( ) method to update / rebuild the widget.
  7. deactivate( ): called when the widget is removed from the widget tree.
  8. dispose( ): called when the state object is permanently removed from the widget tree
    * mounted (false): since the state object is no longer in a tree, framework sets this property to false.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Common Display Widgets

A

Display content that fits within the available space and does not require scrolling. Typically used to display static or dynamic content that can be rendered within the visible area of the screen.

Text: Displays a short piece of text.

Image: Displays an image.

Container: A box that can contain other widgets and be styled with various properties.

Card: Represents a material design card. It can be used to display content in a card-like format.
ListTile: Represents a single fixed-height row that typically contains some text and an optional leading or trailing widget, commonly used in lists.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Common Scrollable Widgets

A

Display content that exceeds the available space and allows the user to scroll through the content. Typically used to display long lists, grids, or other types of content that do not fit entirely within the visible area of the screen.

ListView: Displays a scrolling, linear list of widgets.

GridView: Displays a scrolling, rectangular grid of widgets.

SingleChildScrollView: Provides a scrolling view for a single widget.

CustomScrollView: Allows for complex scrolling behaviors by combining multiple scrollable widgets.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is a Widget Tree?

A

A hierarchical structure of widget objects that represents the user interface.

The root widget (typically a MaterialApp widget) has other widgets added as children to form the overall widget tree.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Build Method vs. BuildContext

A

BuildContext: represents the location of a widget within a widget tree, is used by the Flutter framework to both locate and manipulate widgets within an app.

Build Method: uses a Buildcontext object as a parameter in order to build a widget and its children widgets.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Dart Data Types

A

int: integer values without decimals

double: “floating-point” values with decimals

num: both integer and floating-point values (aka: integers with or without decimals)

String: sequence of characters

bool: boolean values that can only be “true” or “false”

List: an ordered collection of values, AKA: an array. can contain values of any data type, including other lists

Set: an unordered collection of unique values. cannot contain duplicate values

Map: an unordered collection of key-value pairs, where each key must be unique. AKA: dictionaries or hash maps

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Type Annotation

A

Explicitly giving each variable, parameter, and function a data type.

Write the variable data type before the variable or constant name:

int myInteger = 1;

		String name = 'Derrick';
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Type Inference

A

Dart compiler’s ability to determine a variable’s data type without needing it specified by type annotation.

Provides additional information to the Dart compiler about the expected type of a value, and allows for static type checking during compilation rather than run time, which can catch type-related errors early in the development process.

		var name = 'Derrick';    / / Dart will detect this is a String value
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

const vs final

A

Both are immutable (aka: values can’t be changed)

const: values that are determined by the Dart compiler BEFORE runtime and can’t be changed during compile time nor at runtime. Are more performant as values are embedded directly into the compiled code.

final: values that can ONLY be determined AFTER the program starts running and are mutable at runtime but can’t be changed after values are assigned.

Rule of Thumb: use const variables and only use final if the compiler complains.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

var vs dynamic

A

var: a type inference keyword that asks Dart to recognize the data type when declared and Dart will INFER that data type thereafter.

dynamic: a Dart data type that allows a variable’s data type to be determined at runtime as opposed to compile-time and circumvents Dart’s Type Safety checks. Not recommended as it is prone to bug issues.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Type Safe

A

Dart’s ability to catch type-related errors during compile-time before the code is executed and at runtime. It prevents runtime errors due to incorrect and inconsistent data types within the code.

Static Type Checking: Dart’s static type checker analyzes code during compilation and checks that types are used correctly. Otherwise, it will throw an ERROR.

Strongly Typed: must declare the data type of each variable and function parameter as the compiler enforces the correctness of the types used throughout the program.

Runtime: type checks are done when the code begins to execute and throws EXCEPTIONS if there are type errors.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Dynamically-typed vs Statically-typed

A

Dynamically-typed: language where data types can change at runtime.

Statically-typed: language that does not allow data types to change - aka: type safety.

Dart is an Optionally-typed language that is statically-typed by default but can use the “dynamic” keyword to make it Dynamically-typed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Sound Null Safety

A

A feature released in Dart that performs checks to make sure there are no null values where they aren’t expected, the goal is to control where, how, and when null values can be contained within the program.

All types are non-nullable by default and variables can’t contain null values unless you say they can by using the ‘?’ at the end of the data type annotation: String? name;
Null safety checks are performed at compile time to eliminate runtime errors and crashes.

Null values don’t allow the same operations to be performed on them as non-nullable values.

Accessing values: Non-nullable values can be accessed directly using their name, while nullable values require the use of the null-aware operator ‘?’ or the null coalescing operator ‘??’ to safely access their value - - - > (same requirement for checking if a nullable value is null OR to use a nullable value in an expression)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

main( ) vs runApp( )

A

main( ): is the entry point of the app, called when the app is first launched, sets up the initial configuration of the app, typically used to create an instance of “MaterialApp” or “CupertinoApp.”

runApp( ): takes the given widget and makes it the root of the widget tree, is responsible for initializing and running the Flutter application.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Statement vs Expressions

A

Statement: code that tells the computer / compiler what to do.

		print('Hello Dart');  -  simple statement

if (something meets criteria) { - is a complex statement

    			// do something
   		}

Expression: doesn’t do something, rather - it is something like a VALUE or a value that can be calculated.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Dart Keywords

A

class: Used to define a class, which is a blueprint for creating objects in object-oriented programming.

var: Used to declare a mutable (changeable) variable.

dynamic: data type that allows a variable’s data type to be determined at runtime as opposed to compile-time and circumvents Dart’s Type Safety checks.

final: Used to declare an immutable (unchangeable) variable.

const: Used to declare a compile-time constant value.

new: Used to create a new instance of an object.

this: Refers to the current instance of the class, typically used within class methods.

super: Refers to the superclass or parent class, used to call methods or access properties from the superclass.

static: Used to declare class-level members that are accessible without creating an instance of the class.

extends: Used to inherit properties and methods from a superclass in Dart’s class hierarchy.

implements: Used to define interfaces that a class should adhere to.

abstract: Used to declare abstract classes or methods, which cannot be instantiated but can be extended by other classes.

factory: Used to create objects in a different way than the default constructor.

get: Used to define a getter method, which allows accessing a class’s property like a variable.

set: Used to define a setter method, which allows modifying a class’s property like a variable.

async/await: Used for asynchronous programming in Dart, allowing for non-blocking execution of tasks.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

Dart Operators

A

Order of Operations / Operator Precedence: Multiplication and Division are equal. Addition and Subtraction are equal but are lower than multiplication and division. Use parentheses if you want to perform addition or subtraction first.

Arithmetic Operators:

Add ( + ):

Subtract ( - ):

Multiply ( * ):

Divide ( / ):

Modulo Operator ( % ): divides two numbers and returns the REMAINDER

Assignment Operators:

( = ): assigns a value to a variable.

( + = ): adds a value to a variable and assigns the variable to the new value.

( - = ): subtracts a value to a variable and assigns the variable to the new value.

( * = ): multiples a value on a variable and assigns the variable to the new value.

( / = ): divides a value on a variable and assigns the variable to the new value.

( % = ): performs the modulo operation on a variable and assigns the new value.

Comparison Operators:

( == ):  bool, checks for equality between two values.

( != ):  bool, checks for inequality between two values.

( > ):  bool, checks if a value is greater than another value.

( < ):  bool, checks if a value is less than another value.

( >= ):  bool, checks if a value is greater than or equal to another value.

( <= ):  bool, checks if a value is less than or equal to another value.

Logical Operators:

( && ):  returns true if both operands are true.

( || ):  returns true if atleast one of the operands is true.

( ! operand1 ): performed on one operand and negates (reverses) the value of the operand.

Ternary Operator ( expression == true ? set to some value : else set to this value ): simplifies and If/Else Statement.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

Classes

A

Combine data and functions inside of a single structure and are a blueprint or instructions that tells the system how to make an object. An object (aka: instance) is the actual data stored in the computer’s memory.

Functions inside of a class are called methods. Constructors are special class methods that are used to build class objects.

class User {
    String name;
    int age;

    User(this.name, this.age);
}

final user = User( );  / / calls the constructor and creates a User class object

Can access and assign values to class properties (aka: variables) via the dot operator.

Parameter vs. Argument: a parameter is the name and data type that is defined as an input to a function or constructor. An argument is the actual value passed into the function or constructor as an input when they are called.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

Constructors

A

Are special class methods that create (aka: build) instances of a class.

Default - Dart provides by default and has no parameters or arguments. Also known as “implicit” or “unnamed” constructor.

Long-Form - uses a function body { } to initialize class properties: {this.id = id, this.name = name};

Short-Form - uses the THIS keyword to initialize class properties without a function body: User(this.id, this.name);

Named - constructor with a specific name defined by using the dot operator: User.fromJson( )

Factory - creates objects from a class without needing to create a new instance of the class, can also perform functionality before creating a class object. (.fromJson( ) is a factory constructor…)

Forwarding / Redirecting - helps prevent two or more locations initializing class properties by passing in initial values: User.anonymous( ) : this(0, ‘anonymous’);

Constructor Parameters:  Can be optional, named, and required:

Optional: enclose parameters inside of square brackets [ ]

Optional & Named: enclose parameters inside of curly brackets { } within the constructor definition

Named & Required: enclose parameters within curly brackets { } within the constructor definition and use the keyword: required

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

Enums

A

Define a fixed set of constant values for a particular variable.

	enum Makes {
	    Toyota,
	    Honda,
	    Nissan
	}

	void main( ) {
	    Makes myMake = Makes.Toyota;  / / assigns the enum value 
	    print(myMake);  / / outputs Makes.Toyota
	}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

Mixins

A

Allows the reuse of code in multiple classes without requiring each class to inherit from a common superclass.

Use the with keyword after a class name to allow access to the mixin code from within another class.

Example:

mixin Vehicle {
    String make;
    String model;

    void startEngine( ) {
        print(‘Starting engine of $make $model’);
    }

class Car with Vehicle {
    Car(this.make, this.model);

    void drive( ) {
        print(‘Driving $make $model’);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

Functions

A

A named and reusable block { } of code that encapsulates specific instructions or tasks. Can have inputs known as parameters and arguments. Can have an output (a returned value) or no output (a void function).

Functions are usually defined within a class (therein called methods) but can be top-level functions that exist globally (outside the scope of a class) within an application.

Structure of Dart Functions:

String compliment (int number) {
  return ‘$number is a very nice number!’);
}

String is the return type or the type of the output produced by the function

compliment is the function name, should use lowerCamelCase for names

int is the parameter type

number is the parameter name

return is the return value and it must match the data type of the function type; use void if the function doesn’t return anything

The function body is the code between the curly braces { }

Dart supports top-level functions which are functions that don’t exist inside of a class or inside of another function.

31
Q

Callbacks

A

A function that is passed into another function as an argument and is intended to be executed at a later time or in response to a specific event or condition.

The function that receives the callback as an argument can “call back” or invoke the callback function when needed.

/ / Function that adds two numbers and calls a callback function with the sum
void addNumbers(int a, int b, void Function(int) sumHandler) {
int sum = a + b; / / Add two numbers

sumHandler(sum); / / Call the callback function with the sum

}

/ / Callback function to be executed with the sum
void displaySum(int sum) {
print(“Sum: $sum”);
}

/ / Call the addNumbers function with the displaySum callback
void main( ) {
addNumbers(15, 5, displaySum); / / displaySum is passed as the callback
}

32
Q

Scope

A

Refers to the visibility and accessibility of variables, functions, and classes within a program. Determines where a variable, function, or class can be accessed and used within code.

Global Scope: defined outside of any class or function and can be accessed from anywhere in the code by importing the file in which the global variable, function, or class is declared.

Local Scope: defined within a class or function and are only accessed within the same.

33
Q

Arrays

A

A collection of elements of the same type and are zero-indexed meaning the first element has an index of 0.

Types of Arrays:

List: an ordered (indexed) collection of elements of the same type and can grow in size or have a fixed length. Allows duplicate values and supports many operations such as: adding elements, removing elements, iterating over elements…

To create, use the List keyword, a name, and use square brackets [ ]

List<int> myNumbers = [1, 2, 3, 4, 5];

Common operations on Lists:

someList.add( )
someList.addAll( )
someList.insert( )
someList.insertAll( )

someList.remove
someList.removeAt( )
someList.removeLast( )
someList.removeWhere( )
someList.clear( )

someList.first( )
someList.last( )
someList.length( )
someList.sort( )
someList.reversed( )
someList.isEmpty( )
someList.isNotEmpty( )

Set: an unordered (not indexed) collection of unique elements meaning sets do not support having duplicate values.

To create use the Set keyword, a name, and then curly brackets { }

Common Operations on Sets:

someSet.add( )
someSet.addAll( )

someSet.remove( )
someSet.removeAll( )
someSet.clear( )

someSet.first( )
someSet.last( ) someSet.contains( )
someSet.lookup( )

someSet.isEmpty( )
someSet.isNotEmpty( )

Map: an unordered collection of key/value pairs from which a value is retrieved by using its associated unique key. Data is stored and retrieved via keys instead of the elements index.

To create use the Map keyword, a name, and curly brackets { }

Common Operations on Maps:

someMap.addAll( )
someMap.remove( ) someMap.clear( ) someMap.update( )

someMap.containsKey( )
someMap.keys( )
someMap.values( )
someMap.entries( )

someMap.length( )
someMap.isEmpty( )
someMap.isNotEmpty( )

34
Q

Control Flow

A

Refers to the order in which statements and expressions are executed based upon specified conditions.

Types of Control Flow Options:

If/Else Statements: executes a block of code based upon a condition evaluating as true. As long as the condition is true, the code inside of the “if” block will execute.

If it is false, the code inside of the “else” block will execute.

int age = 48;

if (age >= 18) {
    print(“You are an adult.’);
} else {
    print(‘You are a minor.’);
} 

Else/If Statements: execute a block of code associated with multiple conditions.

int score = 85;

if (score >= 90) {
print(“You got an A!”);
} else if (score >= 80) {
print(“You got a B!”);
} else if (score >= 70) {
print(“You got a C!”);
} else if (score >= 60) {
print(“You got a D!”);
} else {
print(“You failed.”);
}

Switch Blocks: are used to provide multiple branches of code execution based on different possible values of an expression.

String fruit = 'apple';

switch (fruit) {
case ‘apple’:
print(‘Selected fruit is an apple.’);
break;
case ‘orange’:
print(‘Selected fruit is an orange.’);
break;
default:
print(‘Selected fruit is not recognized.’);
}

Loops: (see next card)

35
Q

Loops

A

A programming construct (predefined piece of code) that executes a block of code repeatedly for a specific number of times or until a certain condition is met. Used for automating repetitive tasks and for iterating over collections.

Types of Loops:

For loop:  iterates over a collection for a specified number of times.

	for (int i = 0; i < 10; i++) {
	    print(‘Value of i: $i’);
	}

For-in Loop: iterates over a collection without an index as it executes over each element.

List<String> fruits = [‘apple’, ‘banana’, ‘oranges’];

for (String fruit in fruits) {
    print(‘Fruit: $fruit’);
} While Loop:  will iterate over a collection and execute a block of code as long as a condition is true.

int i = 0;

while (i < 5) {
print(‘Value of i: $i’(;
}

Do-While Loop: similar to a While Loop except that the block of code is executed before the condition is checked - means the block of code will execute at least once regardless if the condition is true.

int i = 0;

do {
    print(‘Value of i: $i’);
    i++; 
} while (i < 5);
36
Q

Navigation and Routing

A

Navigation refers to the process of moving from one screen to another.

In Flutter, the Navigator widget manages the navigation stack, which is a collection of routes (screens) that the user has visited.

Routes are screens or pages that a user can navigate to and are represented by the “Route” class.

37
Q

What is a Stream?

A

A source of data that produces values over time and provides a way to handle these values as they become available without blocking the execution of the program.

(think async, await, and asynchronous programming).

Streams are often the results of data sequences which include user-generated events and data read from files.

38
Q

Two Types of Streams

A

Single Subscription Stream: only allows 1 listener at a time, the listener receives all events added to the stream until the stream subscription is canceled or closed.

Broadcast Stream: allows multiple listeners, all listeners receive events until the subscription is canceled or closed.

39
Q

Asynchronous Programming (async, await, Future)

A

Synchronous Programming: functions are called and executed sequentially (in order) and one function must wait until the prior function completes to be executed. Best for simple functions that have immediate results.

Asynchronous Programming (denoted by the use of the async and await keywords): allows for the program to continue to run other functions / tasks while the asynchronous code is waiting for its results. Best for complex tasks / functions that take longer to complete and obtain their results.

Future: represents a value / object that will be available in the future and it allows code to be written that doesn’t block the execution of the program while waiting for it (the future’s) computation or result. Is used with async and await to build asynchronous code.

40
Q

Flow of Data in an App Using Models and Repositories

A

JSON objects are key:value pairs in the form of a Map<String, dynamic> However, they are transferred in String format. This requires that the JSON object be encoded (serialized) into String format before transferring and then decoded (deserialized) upon being received.

  1. The repo makes an http request to the API / Server / Database to fetch some JSON data.
  2. JSON data is received by the repo and is then decoded back into a JSON Object (Map<String, dynamic>) via the jsonDecode method.
  3. An If/Else Statement can be used to check if the response was successful or to throw an exception if it wasn’t.
  4. If successful, return a new instance of the appropriate model class and call that class’s fromJson( ) method and pass in the new decoded JSON object (Map<String, dynamic>)

ALL OF THIS FUNCTIONALITY IS GENERALLY EMBODIED INSIDE OF A REPO METHOD: fetchSomeData( )

41
Q

Data Models

A

Data Models are a representation of the data that an app uses and define the structure and properties of the data that an app works with. Often used to help organize, manipulate, and store that data.

class Person {
final String name;
final int age;
final String email;

Person({required this.name, required this.age, required this.email});

}

42
Q

Repositories

A

Purpose of a Repository: To be the “data source” for an application. It functions to fetch, post, C.R.U.D data and to encode / decode the data (i.e. fromJson and toJson). It also is where the model class objects are instantiated to be accessed by the UI.

How to create a repository and fetch JSON data?

  1. Use the Uri.parse() method to parse the passed in uri String into an uri object.
  2. Make the http request via someMethod() and pass in the parsed uri object - often assigned to a new property: ‘url’.
  3. Assign the http’s response to a new variable like: ‘data’ or ‘response’ or ‘results’.
  4. Decode the http’s response (currently a String) into a JSON object of Map<String, dynamic> via the jsonDecode() method that is part of the dart:convert library.
  5. Serialize/Deserialize the JSON Map<String, dynamic> into model class instances via the fromJson() method automatically generated by the json_annotation and json_serializable packages when running the build_runner command.
43
Q

JSON

A

Stands for JavaScript Object Notation and is a lightweight data interchange format that is easy for humans to read and write, and easy for machines to parse and generate,

Often is the data format used in APIs (Application Programming Interface) like RESTful APIs,

Represented as key-value pairs where each key is a string and each value can be a string, number, boolean, array, or another JSON object.

44
Q

JSON Serialization (Encoding and Decoding)

A

Encoding (serializing): the process of converting a data object or a collection of objects into a JSON formatted string, data object properties are converted into a key-value pair format that can be easily interpreted by other applications.

Decoding (deserializing): process of converting a JSON string into an object or a collection of objects in a programming language, JSON string is parsed and converted into an object that has the same structure as the original object before it was serialized.

45
Q

json_serializable and json_annotation

A

Two packages used for serializing and deserializing JSON data to and from Dart objects.

json_annotation: provides annotations(@something) for generating JSON serialization and deserialization code for Dart classes, defines a set of annotations that are added to a class to indicate how the class should be serialized and deserialized.

json_serializable: a code generator that uses the annotations provided by json_annotation to generate the necessary serialization and deserialization code for the annotated classes, it generates the toJson( ) and fromJson( ) methods used to convert a Dart object to JSON and vice versa.

46
Q

RESTful API and http Requests

A

RESTful APIs: a way for software applications to communicate with each other over the internet using a standard set of rules. REST stands for Representational State Transfer, and it is an architectural style for designing networked applications.

http request: (Hypertext Transfer Protocol) is the foundation of the World Wide Web and is commonly used for communication between web servers and clients, such as mobile apps.

47
Q

What is State Management?

A

The process of managing and updating the state of an application.

State refers to the data that an application needs to keep track of in order to function correctly, such as user input, network requests, and internal data structures.

48
Q

Statement Management Tools

A

Stateful Widgets:

Provider:

BLoC:

GetX:

Redux:

RiverPod:

49
Q

Inherited Widget and Provider Package

A

Inherited Widget: A special type of widget that allows data to be passed down from a parent widget to its descendants in the widget tree. It’s called “inherited” because the data can be inherited by any widget that is below the parent widget in the widget tree, without the need to explicitly pass the data through constructor parameters.

Provider Package: A third-party package in Flutter that simplifies the use of inherited widgets for state management. It provides a way to manage application state and share data across widgets in a more declarative and easy-to-use manner. The provider package is built on top of the inherited widget concept and provides a set of utilities that make it easy to define, access, and update shared data in a Flutter application.

50
Q

What is BLoC Statement Management?

A

BLoC stands for: (Business Logic Component) and serves as the mediator between the presentation layer and the data layer.

The goal is to provide a “separation of concerns” in keeping the business logic separate from the UI and the data layer.

The bloc is where all business logic happens such as if the app is going to fetch or send data and what it will do with the data.

Main Components: BlocProvider, BlocBuilder, BlocListener, BlocConsumer (does both builder and listener), and BlocRepository.

Advantages:

Separation of concerns: BLoC separates the UI from the business logic, making the codebase easier to maintain and test.

Reactive programming: BLoC uses streams to communicate between the UI and business logic layers, making it easier to handle asynchronous events.

Code reusability: BLoC allows for the reuse of business logic components across multiple UI components.

Scalability: BLoC can handle complex app logic and can easily be extended as the app grows.

51
Q

How does BLoC work?

A

Based on the use of streams and event handlers.

Events from the UI (such as user clicks or long presses) are sent to the bloc via an asynchronous stream and are added to the stream via a “sink.”

The bloc then performs business logic on the event and is responsible for querying the data layer via the repository.

Upon receiving a response from the data layer, the bloc can perform any additional business logic on the fetched data before sending it and an updated state back to the UI via an asynchronous stream.

All events are registered by the on<SomeEvent> function which is responsible for converting incoming events into zero or more outgoing states and calling the associated functionality for each event.</SomeEvent>

The on<SomeEvent> API (function) replaced the mapEventToState method.</SomeEvent>

Most events will be user generated

52
Q

What does “business logic” mean?

A

Refers to the processing, manipulation, transformation, and error handling of data that is specific to the business requirements of the application.

It includes the rules, algorithms, and logic that govern how data is processed, validated, transformed, and prepared for presentation in the user interface.

53
Q

BlocProvider vs BlocBuilder vs BlocListener vs BlocConsumer

A

BlocProvider: provides a bloc to its children via the “create” method that returns an instance of a bloc, usually inserted at the top-level of the widget tree, any widgets below it can access the bloc by the “BlocProvider.of” method.

BlocBuilder: rebuilds itself (and its child widgets) whenever the state of the bloc changes, the “builder” method is called whenever the state of the bloc is changed.

BlocListener: listens to changes in state of the bloc and performs side functionality in response to those changes, often used for app navigation and snackbar user notifications.

BlocConsumer: combines BlocBuilder and BlocListener for when rebuilding a widget tree and side functionality is needed in response to state changes.

54
Q

How to Implement BLoC in an App

A
  1. Use the bloc vs code extension to generate a new bloc and relevant folders and files.
  2. Add on<SomeEvent> handlers for each event that emit a given state and the functionality to be performed.</SomeEvent>
  3. Use an If/Else Statement to check that the response was successful and to handle any errors.
55
Q

Flow of Data in an App Using BLoC Pattern

A

User Interaction: The user interacts with the UI by triggering events, such as button clicks, form submissions, or other UI gestures.

Event Dispatching: The UI components dispatch events, also known as “events” or “actions”, to the corresponding BLoCs. These events are usually represented as plain Dart objects, and they contain information about the user’s action.

Event Handling: The BLoCs receive the events and handle them by processing the business logic. This can include making API requests, performing calculations, updating state, and making decisions based on the event data.

State Update: Based on the business logic, the BLoCs update their state. The state represents the current state of the app or a particular feature. The state is usually represented as immutable objects, and it contains all the data needed to rebuild the UI.

State Emitting: The BLoCs emit the updated state to their registered listeners. These listeners are typically the UI components that are interested in the state changes.

UI Rebuilding: The UI components that are listening to the BLoCs receive the updated state and rebuild themselves accordingly. This may involve updating the UI widgets, showing/hiding elements, or triggering animations, based on the new state data.

User Feedback: The updated UI is displayed to the user, and the user receives feedback about the outcome of their action, which may include visual updates or other feedback mechanisms, such as toasts or notifications.

56
Q

What is Dependency Injection (DI)?

A

A software design pattern used in OOP that allows the dependencies of an object to be injected or provided externally, rather than being created or managed by the object itself.

“Dependencies” are objects or services that an object relies on to perform its functions. Are typically passed into an object’s constructor, method, or set as properties, rather than being directly instantiated within the object itself.

For example, imagine a car that needs different parts to function, like an engine, wheels, and a transmission. Instead of building these parts inside the car, you can have them built separately and then installed in the car when needed. This way, you can easily replace or upgrade any part without having to rebuild the entire car.

Similarly, in software development, DI allows you to separate the different parts or “dependencies” of your code, such as objects or services, and provide them externally when needed, instead of creating them inside the code itself. This makes your code more modular, easier to understand, and easier to test.

57
Q

Packages vs Plugins

A

package: a collection of Dart code that can be used to add specific functionality to a Flutter application.

plugin: a type of package that provides access to native platform functionality that is not available in Flutter, typically used to integrate with platform-specific APIs, such as camera access, push notifications, or in-app purchases.

58
Q

Packages and pubspec.yaml

A

package: a collection of reusable code that adds functionality.

pub: is the Dart package manager. Is a command-line tool used to search, install, and manage packages in a Dart project.

pubspec.yaml: a file used to specify the dependencies and configuration of a Dart project.

59
Q

Keys

A

Objects that uniquely identify widgets in a widget tree and help the framework track widgets as the UI changes.

Global Key: a unique widget identifier used to reference a widget from anywhere in the app.

Local Key: a unique widget identifier used to reference a widget but only from within the parent widget that owns it.

Used when state needs to be preserved across rebuilds, when need to update a specific widget without rebuilding the entire UI, or when there are multiple widgets with similar properties and you need to distinguish between them.

60
Q

Unit Tests

A

Tests that validate the behavior of individual units of code like functions, methods, classes, in isolation. Used to ensure that each unit of code is performing as expected / correctly.

61
Q

Error Handling

A

Exception handling: Dart supports exception handling, which allows you to handle runtime errors that occur during the execution of your code. You can use the try, catch, and finally blocks to handle exceptions. The try block contains the code that might throw an exception, and the catch block allows you to specify how to handle the exception when it occurs. The finally block is used to specify code that should always be executed, regardless of whether an exception was thrown or not.

try {
 	    // Code that might throw an exception } catch (e) {
// Exception handling logic } finally {
// Code that should always be executed }
62
Q

Git Version Control

A

Version control is a system that manages changes to a codebase or any other set of files over time. It keeps track of modifications made to files, allowing multiple users to work on the same files simultaneously, and provides the ability to revert to previous versions if needed.

Version control systems typically maintain a repository that stores all changes made to files in the form of revisions or commits.

Each commit represents a snapshot of the entire codebase or set of files at a specific point in time, along with metadata such as the author, date, and commit message describing the changes made.

63
Q

Common Git Commands

A

git init: Initializes a new Git repository, creating a .git directory in the project’s root directory.

git clone: Creates a copy of a remote repository on a local machine.

git add: Adds changes or new files to the staging area, preparing them to be committed.

git commit: Creates a new commit with the changes in the staging area, adding a commit message describing the changes.

git status: Shows the status of the working directory, including any changes or untracked files.

git log: Displays a log of all commits in the repository, showing commit messages, authors, dates, and other details.

git diff: Shows the differences between the working directory and the most recent commit.

git pull: Fetches changes from a remote repository and merges them into the current branch.

git push: Pushes changes to a remote repository, updating the remote branch with the local changes.

git branch: Lists all branches in the repository and shows the currently checked-out branch.

git checkout: Switches to a different branch or commit.

git merge: Merges changes from one branch into another.

git fetch: Fetches changes from a remote repository but does not merge them.

git pull: Fetches changes from a remote repository and merges them into the current branch.

git remote: Shows a list of remote repositories that are connected to the local repository.

64
Q

Persisting Data Locally

A

Data Persistence: the ability of an application or system to store data in a permanent and retrievable way even after the application or system is closed or restarted.

Shared Preferences: allows you to store key-value pairs on the device, and retrieve them later as needed, best for small amounts of data to persist, such as user settings or preferences

Local Database: for larger amounts of structured data, use a local (on device) database such as SQLite or hive, Flutter provides sqflite and hive packages that allows you to interact with local databases.

65
Q

Debugging

A

The process of finding and fixing bugs (issues) in a software application.

Common tools and methods for debugging:

Logging: Using print() or the Dart logging package to output messages to the console to track the flow of execution and variables’ values at different points in your code. This can help you identify incorrect values or unexpected behaviors.

Breakpoints: Setting breakpoints in your code using an Integrated Development Environment (IDE) such as Visual Studio Code or Android Studio. When your code hits a breakpoint during execution, it pauses, allowing you to inspect variables and step through the code to understand its behavior.

Debugging tools: Using the built-in debugging tools provided by Flutter, such as the “Flutter DevTools” browser-based tool or the “debugPaintSizeEnabled” property, which highlights widgets with different colors based on their size on the screen, making it easier to identify layout issues.

Exception handling: Using try-catch blocks to catch and handle exceptions that may occur during runtime. This can help you identify and fix errors that could cause your app to crash.

Hot Reload: Taking advantage of Flutter’s Hot Reload feature, which allows you to make changes to your code and see the results in real-time without having to restart the app. This can help you quickly iterate and fix issues.

Observing widget tree: Using the “Flutter Outline” or “Widget Inspector” tools provided by the IDE to visually inspect the widget tree and understand the structure and hierarchy of widgets in your app. This can help you identify any inconsistencies or unexpected behaviors.

Using assert statements: Adding assert statements in your code to validate assumptions about variables, functions, or other parts of your code. When an assert statement fails, an error is thrown, helping you identify and fix issues.

Analyzing logs and error messages: Reviewing logs and error messages generated by your app or the Dart runtime to identify any warnings, errors, or exceptions that can help you pinpoint the root cause of the issue.

66
Q

………….. BLANK ……………..

A
67
Q

………….. BLANK ……………..

A
68
Q

………….. BLANK ……………..

A
69
Q

………….. BLANK ……………..

A
70
Q

Favorite Apps Built with Flutter

A

Toyota

Groupon

eBay Motors

Realtor.com

71
Q

[INTERVIEW PROBLEM] Array of ints, Return Highest Value

A

int findLargest(List<int> numbers) {
int largest = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > largest) {
largest = numbers[i];
}
}
return largest;
}</int>

72
Q

What Does It Mean to “Register Services” or “Register Blocs”?

A

SERVICES: services are used to encapsulate and manage specific functionality or operations like data fetching, API communications like Repositories, or local storage.

REGISTER SERVICES: (specific to get_it) process of creating an instance of the service class and making it available for use throughout the app, usually done during app startup such as the main( ) function.

PACKAGE: get_it

73
Q

Steps for Setting Up a Data Layer Using Model Classes and Repositories (not using BLoC)

A
  1. Add API Key to a .env file
  2. Add .env file to the .gitignore file.
  3. Add json_annotation, json_serializable, build_runner, http, and dotenv packages to pubspec.yaml.
  4. Create model class using appropriate json annotations and sub-classes for any nested json objects
  5. Add ‘part.<model_file_name>.g.dart' below imports.</model_file_name>
  6. Run the build_runner command: flutter packages pub run build_runner build (or watch)–delete-conflicting-outputs.
  7. Create a repository with a fetchSomeData( ) method that makes an http request, decodes the json String via the jsonDecode( ) method.
  8. Use an If/Else Statement to check the status of the http response and to return an instance of the model class by passing in the newly decoded JSON object. Or, to throw an exception if the response was unsuccessful.
74
Q

What are the Different Build Modes in Flutter?

A

debug: app is set up for debugging on physical device or on an emulator / simulator.

profile: some debugging abilities are maintained to allow profiling app’s performance.

release: for deploying the app, when you want maximum performance and a minimal footprint.