Code

Scripts - Common Naming

Flutter Firebase Auth Sample Integration

Flutter Firebase Auth Sample Integration

Flutter - Riverpod

Flutter - Riverpod

References

Flutter - State Management

Local state - State that can be contained within a single widget. Local or ephemeral state. setState & Stateful widget. State that only effects a single widget.

Global / Shared state - State that is share across multiple widgets. Options include: Flutters built in Inherited Widget. Change Notifier, Value Notifier, StreamBuilder & FutureBuilder

Best practice is to check for 4 state of UI:

  • Data
  • NoData
  • Error
  • Loading

Stream Builder offers some capabilities but its clunky

Flutter - UI Quick Reference

Flutter - UI Quick Reference

Rounded Corners

Container(
	decoration: BoxDecoration(		
		borderRadius: BorderRadius.circular(12),
	),
)

Font Style

Text(
	"MyLabel",
	
	style: TextStyle(
		fontWeight: FontWeight.bold,
		fontSize: 20,
	),
),

Percent indicator

percent_indicator: ^4.2.2

CircularPercentIndicator(
	radius: 20,
	percent: 0.7,
),
References

Flutter - MacOS Build

Flutter - MacOS Build

To make a local executable for mac:

From the terminal type flutter build macos

The app is create under: build/macos/Products/Release/{yourapp}.app

[!tip]+ Target level issues The Mac Podfile needed to be updated: At the top uncomment the first line and update to 10.12 platform :osx, ‘10.12’ Also Podfile post_install do |installer| installer.pods_project.targets.each do |target| flutter_additional_macos_build_settings(target) #Add this section target.build_configurations.each do |config| config.build_settings[‘MACOSX_DEPLOYMENT_TARGET’] = ‘10.12’ end end end

Flutter for MacOS Distribution - Firestore Bug

Flutter for MacOS Distribution - Firestore Bug

I was building a app testing firestore and hapened to be using MacOS Desktop as the deploy target.

Come to find out it wasn’t connecting to the server but was using local cache instead.

Running the same app with ios worked fine

I haven’t figured it out yet. some references talk about setting entitlements

https://docs.flutter.dev/desktop#entitlements-and-the-app-sandbox https://stackoverflow.com/questions/63044652/how-do-i-get-a-flutter-project-running-on-macos-to-successfully-use-firestore

FIXED:

I needed to update it in xcode

Flutter - HiveDB

View Source Code Here

Hive DB

This example explores the use of HiveDB for local storage in dart & flutter

Dependencies

HiveDB requires four entries in your pubspec.yaml. Two belong under the standard dependencies section and another 2 are required in the dev section. These last two are used to generate the adapters from the command line

dependencies:
  flutter:
    sdk: flutter
  
  # hive database
  hive: ^2.0.3
  hive_flutter: ^1.0.0

dev_dependencies:
  flutter_test:
    sdk: flutter

  # hive database
  build_runner: ^1.12.2
  hive_generator: ^1.0.1

Initialize HiveDB

In both flutter and Dart you need to initialize the database and register adapters.

Flutter - JSON from File

View Source Code Here

Flutter JSON from file

This example loads a sample dataset from a file and displays a random entry in the UI

Loading data from a static json file

Register the file in the assets section of pubspec.yaml

assets:
  - assets/data/quotes.json

Import Services and convert

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

Load data into a variable

class _MyHomePageState extends State<MyHomePage> {
  List _quotes = [];
  

  @override
  void initState() {
    readJson();
    
    super.initState();
  }
...

  void readJson() async {
    final String response =
        await rootBundle.loadString('assets/data/quotes.json');
    final data = await json.decode(response);

    setState(() {
      _quotes = data;
    });
  }

Display a random quote

Flutter - List Sorting

View Source Code Here

Flutter List Sorting

This example demonstrates how to sort a List of items.

Given a list of users and a sort order (isDecending)

bool isDecending = false;

List<String> users = [
    'Bret',
    'Antonette',
    'Samantha',
    'Karianne',
    'Kamren',
    'Leopoldo',
    'Elwyn',
    'Maxime',
    'Delphine',
    'Kattie',
    'Moriah',
    'Clementina',
    'Kurtis',
    'Aaron'
  ];

You can sort the list with the compareTo() function as follows.

final sortedUsers = users..sort(
    (userA, userB) =>
        isDecending ? 
            userB.compareTo(userA) : //desc 
            userA.compareTo(userB)); //asc
          

[[../../../_notes/code/Flutter|Back to Flutter]]

Flutter - YouTube Player

View Source Code Here

YouTube Player

This example explores playing youtube videos inside flutter apps.

The package youtube_player_flutter has a sister project called youtube_player_iframe both located in the same repo at https://github.com/sarbagyastha/youtube_player_flutter. It’s important to note which instructions you’re looking at. The top level readme was focused on the iframe variation at time of writing.

Controller

A controller is used to retrieve the video and associated metadata.

YoutubePlayerController yt = YoutubePlayerController(
    initialVideoId: "FuiafRLTbEQ", 
    flags: YoutubePlayerFlags(
      hideControls: false,
      autoPlay: true,
      mute: false,
    ),
  );

The value initialVideoId is only used during the creation of the controller. To change the video later you can use the load() method as in the setState call below. Alternatively you can queue up a video to play next using the cue() method

Flutter - List Filtering

List filtering

View Source Code Here

To get a subset of items from a List in flutter you can use the List.where() method. The method loops over all entries in the List passing them to a custom function you define where you can decide what is returned for that item.

Simple boolean

The following code creates a subset list called openTodos with items from allTodos that are not completed.

List<Todo> openTodos = allTodos.where((todo) => 
    !todo.completed).toList();

Don’t forget to convert it to a List with .toList() at the end

Flutter - Repository Pattern

Flutter Repository Pattern

View Source Code Here

This repo demonstrates using the repository pattern for layering your architecture.

In this design the view utilizes a generic interface to get and set data against the repository. That specification can be setup in an abstract class such as:

abstract class BookRepository {
  Stream<List<Book>> getAll();
  Future<Book?> getOne(int id);
  Future<void> insert(Book book);
  Future<void> update(Book book);
  Future<void> delete(int id);
}

This class is the implemented by with the concrete class

Flutter - ListView Dynamic Data

ListView with Dynamic Data

View Source Code Here

This example implements the common use case of displaying a ListView using a dynamic set of data from an external source.

For this example the data is provided by a method called getMockItems which includes static data but could just as easily be dynamic data from an API or other data source.

List<Item> getMockItems() {
    return [
      Item(name: "name", text: "text"),
      Item(name: "name", text: "text"),
      Item(name: "name", text: "text"),
      Item(name: "name", text: "text"),
      Item(name: "name", text: "text"),
      Item(name: "name", text: "text"),
    ];
  }

To use the ListView in this model you’ll use the length of the List for itemCount:. Next, itemBuilder: is called for each entry in the list when it’s time to display it. In this example, the index is provided to a function called buildListItem which returns the view of a single entry.

Flutter Firebase Setup For iOS

Setting up a Flutter iOS app to use Firebase

Flutter Firebase Auth Setup for Android

Flutter Firebase Auth Setup for Android

Flutter - Top 10 Tips for Flutter in VS Code

Top 10 Tips for Flutter in VS Code

Flutter Rename Application Package & BundleID

Renaming the Application Package & BundleID after project creation

Flutter Initializing New Applications

Setting up new Flutter from the command line

Artifact Registry in Google Cloud

Flutter - Classes & Constructors

Classes & Constructors

class Person {
  final String first;
  final String last;
  final String email;

  Person : first = "none"; // initializer list  assigns variables before the constructor runs
  
  Person(n) : first = n { print(n) } // Initializer with constructor (note {} replaces the ;)

  Person(this.first) // automatic assignment to instance var in constructor
  
  Person({this.first}) // curly braces make the value optional
  
  Person.myName(this.first) // Named constructors provide extra clarity and are needed for multiple contstructors



  //example - Named constructor taking a general map and email
  Person.fromMap(Map<String, dynamic> map, {this.email}) 
      : assert(map['first'] != null),
        assert(map['last'] != null),
        first = map['first'],
        last = map['last'];
 

}

More details in this good article

Flutter - CLI New App

Create a New Application

  • Create a new app
flutter create todo
  • or with an org
flutter create --org run.cgrant todo

Flutter - Cocopods issues wite firebase - M1 issue

Had issues getting Flutter to connect to firebase. Had some cocopods issues. This seems to be a M1 Mac issue

Found a fix on this video https://www.youtube.com/watch?v=iWIiXADqsm0

install ffi:

sudo arch -x86_64 gem install ffi
cd ios
arch -x86_64 pod install --repo-update
cd ..

in the project dir

flutter clean
flutter pub get

be sure to properly initialize firebase

void main() async {
	WidgetsFlutterBinding.ensureInitialized();
	await Firebase.initializeApp(
		options: DefaultFirebaseOptions.currentPlatform,
	);
	runApp(MyApp());
}

Update Theres a new pattern

Flutter - Code Basics

Code Basics

the main.dart file executes the app with the following convention

void main() => runApp(MyApp());

MyApp() is a class that extends either a StatelessWidget or StatefulWidget. In general if the content of the screen is not going to change its display it should be stateless. StatfullWidgets require additional code we’ll review in a minute.

StatelessWidget

the basic class definition is simple

class MyApp extends StatelessWidget {

}

We’re going to override the build method for the Stateless Widget and return our main display.

Flutter - Connecting to Firestore

Flutter - Connecting to Firestore

[[../../../_notes/code/Flutter]]

Make sure you’ve configured your project using the instructions in [[Flutter - Firebase Setup]]

Add the dependency to your pubspec.yaml

flutter pub add cloud_firestore

Make sure to run packages get to pull the new dependencies

iOS additional Config

I had an issue when trying to debug my app. Error read [!] Automatically assigning platform iOS with version 9.0 on target Runner because no platform was specified. Solution found on this site states you should: Open the Podfile and uncomment the second line. Set the platform :ios to 11

Flutter - Creating Packages and reuseable modules


title: Flutter - Creating Packages and reuseable modules tags: [flutter]


how to create packages for reuse across multiple apps

Good write up on it: https://www.youtube.com/watch?v=ZABb7PTkT58

Flutter - Embed Dartpad

Flutter - Embed Dartpad

Flutter - File & Folder Structures

Key Files & Folders

Before getting into the coding lets refresh on the core concepts

  • Lib: the core source files are under /lib
  • Main.dart: Typically there’s a minimal main.dart file
  • Pubspec: the main config file is /pubspec.yaml
    • Contains the package name of this app
    • Contains dependency definitions

[[../../../_notes/code/Flutter|Back to Flutter]]

Folder structure convention

[!note] Note - personal convention I’ve moved to using “Screens” and “Components” Screens instead of Pages. Screens have skaffold - easy to remember Components not widgets. Components are a broader industry term

Flutter - Firebase Setup

Getting started

It used to be somewhat challenging to configure [[Firebase]] and [[../../../_notes/code/Flutter]]. Now though they’ve provided a new flutterfire CLI to assist and it’s super easy now.

Install it with

npm install -g firebase-tools
dart pub global activate flutterfire_cli

Configure your project

Create a new flutter project and configure it with the command line


flutter create testapp
cd testapp

flutter pub add firebase_core

flutterfire configure

This step creates the config in firebase for your platform and puts the related config in a firebase_options.dart file.

Flutter - firestore-connections

2 Connecting to firestore

First add the dependency

open the file pubspec.yaml and add the dependency for cloud_firestore

dependencies:
  flutter:
    sdk: flutter
  cloud_firestore: ^0.8.2

Make sure to run packages get to pull the new dependencies

Connecting Android

Once you have your firebase project and firestore database created, you’ll need to add the keys for both Android and iOS. This section will just cover android

Create a new app in firebase and choose the android type.

Flutter - ios-google-signin

tips

Google sign in on ios crashes for me

this was a good thread https://github.com/flutter/flutter/issues/44564

As noted in that thread, I needed to add a url scheme as mentioned here https://developers.google.com/identity/sign-in/ios/start-integrating#add_a_url_scheme_to_your_project

Flutter - Model Conventions

Once you review this, go look at [Freezed](https://pub.dev/packages/freezed) to simlify creation with generated classes

Utilize a lib/models folder for your classes Utilize initializer lists for simple setters instead of full constructors Utilize named constructors like .fromMap() to initialize objects from various inputs

Provide a toString method for simple outputs Provide serialization methods like toMap and toJSON to make conversions easier later

lib/models/record.dart

class Record {
  final String name;
  final int votes;
  final DocumentReference reference;

  Record.fromMap(Map<String, dynamic> map, {this.reference})
      : assert(map['name'] != null),
        assert(map['votes'] != null),
        name = map['name'],
        votes = map['votes'];

  Record.fromSnapshot(DocumentSnapshot snapshot)
      : this.fromMap(snapshot.data, reference: snapshot.reference);

  @override
  String toString() => "Record<$name:$votes>";

  Map toMap() {
    return {
      'name': name,
      'votes': votes,
    };
  }
}

[[../../../_notes/code/Flutter|Back to Flutter]]

Flutter - Model Conventions

Flutter Model Conventions

Utilize a lib/models folder for your classes Utilize initializer lists for simple setters instead of full constructors Utilize named constructors like .fromMap() to initialize objects from various inputs

Provide a toString method for simple outputs Provide serialization methods like toMap and toJSON to make conversions easier later

lib/models/record.dart

class Record {
  final String name;
  final int votes;
  final DocumentReference reference;

  Record.fromMap(Map<String, dynamic> map, {this.reference})
      : assert(map['name'] != null),
        assert(map['votes'] != null),
        name = map['name'],
        votes = map['votes'];

  Record.fromSnapshot(DocumentSnapshot snapshot)
      : this.fromMap(snapshot.data, reference: snapshot.reference);

  @override
  String toString() => "Record<$name:$votes>";

  Map toMap() {
    return {
      'name': name,
      'votes': votes,
    };
  }
}

Flutter - Packages and Imports

Packages and Imports

Files can reference each other with standard paths following the package name.

Assuming the following structure

flutter_my_demo
- pubpsec.yaml (name: flutter_my_demo)
- lib/
    - main.dart
    - screens/
        - homepage/
            homepage.dart

You can access the homepage dart file with:

import 'package:flutter_my_demo/screens/homepage/homepage.dart'; or with relative paths (including ../.. syntax) import 'screens/homepage/homepage.dart';

[[../../../_notes/code/Flutter|Back to Flutter]]

Flutter Connecting to Firestore

Flutter Connecting to Firestore

[[../../../_notes/code/Flutter]]

First add the dependency

open the file pubspec.yaml and add the dependency for cloud_firestore

dependencies:
  flutter:
    sdk: flutter
  cloud_firestore: ^0.8.2

Make sure to run packages get to pull the new dependencies

Connecting Android

Once you have your firebase project and firestore database created, you’ll need to add the keys for both Android and iOS. This section will just cover android

Create a new app in firebase and choose the android type.

Flutter Google SignIn with iOS

Flutter Google SignIn with iOS

[[../../../_notes/code/Flutter]]

Google sign in on ios crashes for me

this was a good thread

https://github.com/flutter/flutter/issues/44564

As noted in that thread, I needed to add a url scheme as mentioned here

https://developers.google.com/identity/sign-in/ios/start-integrating#add_a_url_scheme_to_your_project

  • Create your app
    • Bundle identifier from xcode
  • Download services file
    • Drag to Runner/Runner in xcode
  • Add URL scheme
    • Get reverse ID from info.plist

Flutter Home

Flutter Development

You forgot everything again didn’t you 🙂

OK let’s try to get you back up to speed quicker this time.

Go through the install process if you’re really starting fresh. Make sure you’ve got the various plugins installed in vscode and you’re ready to go.

Other wise do flutter upgrade to get things to the latest.

Before you try digging into old projects, code some simple apps again to get refreshed on stuff.

Flutter ios-google-signin

Google sign in on ios crashes for me

[[../../../_notes/code/Flutter]]

this was a good thread https://github.com/flutter/flutter/issues/44564

As noted in that thread, I needed to add a url scheme as mentioned here https://developers.google.com/identity/sign-in/ios/start-integrating#add_a_url_scheme_to_your_project

Flutter TOC

Flutter

Getting started

  • Install Flutter
  • [[flutter-top-10-vs-code-tips|Setup VS Code]]
  • [[../Flutter - File & Folder Structures|Review File and Folder Structures]]
  • [[../Flutter - Code Basics|Review Basic Flutter Coding]]
  • [[../Flutter - Classes & Constructors|Classes & Constructors]]
  • [[../Flutter - Packages and Imports|Packages & Imports]]

Build an application

  • [[Flutter - CLI New App |Create a new app]]
  • [[Flutter - Model Conventions 2|Create a Model]]
  • [[../Flutter - JSON from File|Load JSON Data from a file]]
  • [[../Flutter - ListView Dynamic Data|Display Data in ListView]]
  • [[../Flutter - List Sorting|Add Sorting on the ListView]]
  • [[../Flutter - List Filtering|Add Filtering on the ListView]]
  • [[../Flutter - Repository Pattern|Abstract the data layer]]
  • [[../Flutter - HiveDB|Add local persistence with HiveDB]]

Architectures & System Design

  • [[Flutter - Model Conventions 2]]
  • [[../Flutter - Repository Pattern]]

State Management

  • [[../Flutter - State Management]]
  • [[../Flutter - Riverpod]]

Firebase

Setup

  • [[../Flutter - Firebase Setup]]

Firebase Auth

  • [[flutter-firebase-auth-setup-for-android]]

Firestore

Google Sign-in

All Notes

TABLE
title
FROM #flutter