Billy Chandler

Billy Chandler

1569656270

Getting Started with BLoC in Flutter

Overview

Bloc Architecture

The goal of this package is to make it easy to implement the BLoC Design Pattern (Business Logic Component).

This design pattern helps to separate presentation from business logic. Following the BLoC pattern facilitates testability and reusability. This package abstracts reactive aspects of the pattern allowing developers to focus on converting events into states.

Glossary

Events are the input to a Bloc. They are commonly UI events such as button presses. Events are dispatched and then converted to States.

States are the output of a Bloc. Presentation components can listen to the stream of states and redraw portions of themselves based on the given state (see BlocBuilder for more details).

Transitions occur when an Event is dispatched after mapEventToState has been called but before the Bloc’s state has been updated. A Transition consists of the currentState, the event which was dispatched, and the nextState.

BlocSupervisor oversees Blocs and delegates to BlocDelegate.

BlocDelegate handles events from all Blocs which are delegated by the BlocSupervisor. Can be used to intercept all Bloc events, transitions, and errors. It is a great way to handle logging/analytics as well as error handling universally.

Bloc Interface

initialState is the state before any events have been processed (before mapEventToState has ever been called). initialState must be implemented.

mapEventToState is a method that must be implemented when a class extends Bloc. The function takes the incoming event as an argument. mapEventToState is called whenever an event is dispatched by the presentation layer. mapEventToState must convert that event into a new state and return the new state in the form of a Stream which is consumed by the presentation layer.

dispatch is a method that takes an event and triggers mapEventToState. dispatch may be called from the presentation layer or from within the Bloc (see examples) and notifies the Bloc of a new event.

transformEvents is a method that transforms the Stream<Event> along with a next function into a Stream<State>. Events that should be processed by mapEventToState need to be passed to next. By default asyncExpand is used to ensure all events are processed in the order in which they are received. You can override transformEvents for advanced usage in order to manipulate the frequency and specificity with which mapEventToState is called as well as which events are processed.

transformStates is a method that transforms the Stream<State> into a new Stream<State>. By default transformStates returns the incoming Stream<State>. You can override transformStates for advanced usage in order to manipulate the frequency and specificity at which transitions (state changes) occur.

onEvent is a method that can be overridden to handle whenever an Event is dispatched. It is a great place to add bloc-specific logging/analytics.

onTransition is a method that can be overridden to handle whenever a Transition occurs. A Transition occurs when a new Event is dispatched and mapEventToState is called. onTransition is called before a Bloc’s state has been updated. It is a great place to add bloc-specific logging/analytics.

onError is a method that can be overridden to handle whenever an Exception is thrown. By default all exceptions will be ignored and Bloc functionality will be unaffected. It is a great place to add bloc-specific error handling.

dispose is a method that closes the event and state streams. Dispose should be called when a Bloc is no longer needed. Once dispose is called, events that are dispatched will not be processed and will result in an error being passed to onError. In addition, if dispose is called while events are still being processed, any states yielded after are ignored and will not result in a Transition.

BlocDelegate Interface

onEvent is a method that can be overridden to handle whenever an Event is dispatched to any Bloc. It is a great place to add universal logging/analytics.

onTransition is a method that can be overridden to handle whenever a Transition occurs in any Bloc. It is a great place to add universal logging/analytics.

onError is a method that can be overriden to handle whenever an Exception is thrown from any Bloc. It is a great place to add universal error handling.

Usage

For simplicity we can create a CounterBloc like:

class CounterBloc extends Bloc<CounterEvent, int> {
  @override
  int get initialState => 0;

  @override
  Stream<int> mapEventToState(CounterEvent event) async* {
    switch (event) {
      case CounterEvent.decrement:
        yield currentState - 1;
        break;
      case CounterEvent.increment:
        yield currentState + 1;
        break;
    }
  }
}

Our CounterBloc converts CounterEvents to integers.

As a result, we need to define our CounterEvent like:

enum CounterEvent { increment, decrement }

Then we can dispatch events to our bloc like so:

void main() {
  final counterBloc = CounterBloc();

  counterBloc.dispatch(CounterEvent.increment);
  counterBloc.dispatch(CounterEvent.increment);
  counterBloc.dispatch(CounterEvent.increment);

  counterBloc.dispatch(CounterEvent.decrement);
  counterBloc.dispatch(CounterEvent.decrement);
  counterBloc.dispatch(CounterEvent.decrement);
}

As our app grows and relies on multiple Blocs, it becomes useful to see the Transitions for all Blocs. This can easily be achieved by implementing a BlocDelegate.

class SimpleBlocDelegate extends BlocDelegate {
  @override
  void onTransition(Bloc bloc, Transition transition) {
    super.onTransition(bloc, transition);
    print(transition);
  }
}

Now that we have our SimpleBlocDelegate, we just need to tell the BlocSupervisor to use our delegate in our main.dart.

void main() {
  BlocSupervisor.delegate = SimpleBlocDelegate();

  final counterBloc = CounterBloc();

  counterBloc.dispatch(CounterEvent.increment); // { currentState: 0, event: CounterEvent.increment, nextState: 1 }
  counterBloc.dispatch(CounterEvent.increment); // { currentState: 1, event: CounterEvent.increment, nextState: 2 }
  counterBloc.dispatch(CounterEvent.increment); // { currentState: 2, event: CounterEvent.increment, nextState: 3 }

  counterBloc.dispatch(CounterEvent.decrement); // { currentState: 3, event: CounterEvent.decrement, nextState: 2 }
  counterBloc.dispatch(CounterEvent.decrement); // { currentState: 2, event: CounterEvent.decrement, nextState: 1 }
  counterBloc.dispatch(CounterEvent.decrement); // { currentState: 1, event: CounterEvent.decrement, nextState: 0 }
}

At this point, all Bloc Transitions will be reported to the SimpleBlocDelegate and we can see them in the console after running our app.

If we want to be able to handle any incoming Events that are dispatched to a Bloc we can also override onEvent in our SimpleBlocDelegate.

class SimpleBlocDelegate extends BlocDelegate {
  @override
  void onEvent(Bloc bloc, Object event) {
    super.onEvent(bloc, event);
    print(event);
  }

  @override
  void onTransition(Bloc bloc, Transition transition) {
    super.onTransition(bloc, transition);
    print(transition);
  }
}

If we want to be able to handle any Exceptions that might be thrown in a Bloc we can also override onError in our SimpleBlocDelegate.

class SimpleBlocDelegate extends BlocDelegate {
  @override
  void onEvent(Bloc bloc, Object event) {
    super.onEvent(bloc, event);
    print(event);
  }

  @override
  void onTransition(Bloc bloc, Transition transition) {
    super.onTransition(bloc, transition);
    print(transition);
  }

  @override
  void onError(Bloc bloc, Object error, StackTrace stacktrace) {
    super.onError(bloc, error, stacktrace);
    print('$error, $stacktrace');
  }
}

At this point, all Bloc Exceptions will also be reported to the SimpleBlocDelegate and we can see them in the console.

Dart Versions

  • Dart 2: >= 2.0.0

Examples

  • Counter - an example of how to create a CounterBloc in a pure Dart app.

Maintainers

#flutter #dart #mobile-apps

What is GEEK

Buddha Community

Getting Started with BLoC in Flutter

Google's Flutter 1.20 stable announced with new features - Navoki

Flutter Google cross-platform UI framework has released a new version 1.20 stable.

Flutter is Google’s UI framework to make apps for Android, iOS, Web, Windows, Mac, Linux, and Fuchsia OS. Since the last 2 years, the flutter Framework has already achieved popularity among mobile developers to develop Android and iOS apps. In the last few releases, Flutter also added the support of making web applications and desktop applications.

Last month they introduced the support of the Linux desktop app that can be distributed through Canonical Snap Store(Snapcraft), this enables the developers to publish there Linux desktop app for their users and publish on Snap Store.  If you want to learn how to Publish Flutter Desktop app in Snap Store that here is the tutorial.

Flutter 1.20 Framework is built on Google’s made Dart programming language that is a cross-platform language providing native performance, new UI widgets, and other more features for the developer usage.

Here are the few key points of this release:

Performance improvements for Flutter and Dart

In this release, they have got multiple performance improvements in the Dart language itself. A new improvement is to reduce the app size in the release versions of the app. Another performance improvement is to reduce junk in the display of app animation by using the warm-up phase.

sksl_warm-up

If your app is junk information during the first run then the Skia Shading Language shader provides for pre-compilation as part of your app’s build. This can speed it up by more than 2x.

Added a better support of mouse cursors for web and desktop flutter app,. Now many widgets will show cursor on top of them or you can specify the type of supported cursor you want.

Autofill for mobile text fields

Autofill was already supported in native applications now its been added to the Flutter SDK. Now prefilled information stored by your OS can be used for autofill in the application. This feature will be available soon on the flutter web.

flutter_autofill

A new widget for interaction

InteractiveViewer is a new widget design for common interactions in your app like pan, zoom drag and drop for resizing the widget. Informations on this you can check more on this API documentation where you can try this widget on the DartPad. In this release, drag-drop has more features added like you can know precisely where the drop happened and get the position.

Updated Material Slider, RangeSlider, TimePicker, and DatePicker

In this new release, there are many pre-existing widgets that were updated to match the latest material guidelines, these updates include better interaction with Slider and RangeSliderDatePicker with support for date range and time picker with the new style.

flutter_DatePicker

New pubspec.yaml format

Other than these widget updates there is some update within the project also like in pubspec.yaml file format. If you are a flutter plugin publisher then your old pubspec.yaml  is no longer supported to publish a plugin as the older format does not specify for which platform plugin you are making. All existing plugin will continue to work with flutter apps but you should make a plugin update as soon as possible.

Preview of embedded Dart DevTools in Visual Studio Code

Visual Studio code flutter extension got an update in this release. You get a preview of new features where you can analyze that Dev tools in your coding workspace. Enable this feature in your vs code by _dart.previewEmbeddedDevTools_setting. Dart DevTools menu you can choose your favorite page embed on your code workspace.

Network tracking

The updated the Dev tools comes with the network page that enables network profiling. You can track the timings and other information like status and content type of your** network calls** within your app. You can also monitor gRPC traffic.

Generate type-safe platform channels for platform interop

Pigeon is a command-line tool that will generate types of safe platform channels without adding additional dependencies. With this instead of manually matching method strings on platform channel and serializing arguments, you can invoke native class and pass nonprimitive data objects by directly calling the Dartmethod.

There is still a long list of updates in the new version of Flutter 1.2 that we cannot cover in this blog. You can get more details you can visit the official site to know more. Also, you can subscribe to the Navoki newsletter to get updates on these features and upcoming new updates and lessons. In upcoming new versions, we might see more new features and improvements.

You can get more free Flutter tutorials you can follow these courses:

#dart #developers #flutter #app developed #dart devtools in visual studio code #firebase local emulator suite in flutter #flutter autofill #flutter date picker #flutter desktop linux app build and publish on snapcraft store #flutter pigeon #flutter range slider #flutter slider #flutter time picker #flutter tutorial #flutter widget #google flutter #linux #navoki #pubspec format #setup flutter desktop on windows

Terry  Tremblay

Terry Tremblay

1598396940

What is Flutter and why you should learn it?

Flutter is an open-source UI toolkit for mobile developers, so they can use it to build native-looking** Android and iOS** applications from the same code base for both platforms. Flutter is also working to make Flutter apps for Web, PWA (progressive Web-App) and Desktop platform (Windows,macOS,Linux).

flutter-mobile-desktop-web-embedded_min

Flutter was officially released in December 2018. Since then, it has gone a much stronger flutter community.

There has been much increase in flutter developers, flutter packages, youtube tutorials, blogs, flutter examples apps, official and private events, and more. Flutter is now on top software repos based and trending on GitHub.

Flutter meaning?

What is Flutter? this question comes to many new developer’s mind.

humming_bird_dart_flutter

Flutter means flying wings quickly, and lightly but obviously, this doesn’t apply in our SDK.

So Flutter was one of the companies that were acquired by **Google **for around $40 million. That company was based on providing gesture detection and recognition from a standard webcam. But later when the Flutter was going to release in alpha version for developer it’s name was Sky, but since Google already owned Flutter name, so they rename it to Flutter.

Where Flutter is used?

Flutter is used in many startup companies nowadays, and even some MNCs are also adopting Flutter as a mobile development framework. Many top famous companies are using their apps in Flutter. Some of them here are

Dream11

Dream11

NuBank

NuBank

Reflectly app

Reflectly app

Abbey Road Studios

Abbey Road Studios

and many more other apps. Mobile development companies also adopted Flutter as a service for their clients. Even I was one of them who developed flutter apps as a freelancer and later as an IT company for mobile apps.

Flutter as a service

#dart #flutter #uncategorized #flutter framework #flutter jobs #flutter language #flutter meaning #flutter meaning in hindi #google flutter #how does flutter work #what is flutter

Brain  Crist

Brain Crist

1603616400

Flutter Bloc State Management

A flutter bloc state management series that will walk you through from all the basics of streams to advance state management tools like flutter_bloc/bloc package

Let’s start by understanding what we mean by state management and why should we care about it in the first place.

What Exactly Is State management ?

In simple words, state means data or the current information the user can see or manipulate.

For eg: Interface controls such as text fields, OK buttons, radio buttons, etc. To maintain these state of data like weather a button is pressed or not what is the current text in the text field or is a toggle button on or off, These data which user generally see or interacts with or generates on some event is called the state and the term used for maintaining all these information(state) is called state management.

The problem :

State management can become very messy when the application grows, simple tools like setState in flutter can’t be the solution for managing large changes at once and tools like inherited widget can create a lot of boilerplate code.

The Solution :

To overcome the above problem we can simply use tools like flutter_bloc/bloc these packages are created by the community are pretty useful for reducing boilerplate code and can be very easy to implement.

Before going deep into the flutter_bloc package we need to make our basics clear these basics includes :

_:: _streams

:: cubit

:: bloc

Streams :

A stream is a sequence of asynchronous data. Streams are just like water hose which have a sink and a drain, Which we can use to provide and retrieve data from streams. To fully understand the concept of bloc we will first need to understand the core features and basic application of streams in Dart.

As we know the basic definition of streams lets generate our own stream using the yield keyword.

Image for post

Image for post

using yield to generate stream’s

In the above example, we have a function getRandomNumberStream this function is present in “lib\streamGenerators.dart” (It’s better to clone the repo and take a look at the structure of the program) which output streams we have specified that by using *async. **Then we have a Future.delayed() which delays our execution for the first run for 1000 ms and then 500 ms for every other subsequent execution. Then we output(yield) the value.

What** yield **does it basically output the data in the form of a stream, So this function is going to be our go-to for all our need for streams in this first series.

Now let me brief about all the basic functions that are available with streams.

  • .map: .map helps us to map the event that we are getting from the stream by passing them to a function. ex
StreamGenerators.getRandomNumberStream(10).map((event) => "This event --$event-- is mapped");

op:
This event --$0-- is mapped
This event --$1-- is mapped
This event --$2-- is mapped
This event --$3-- is mapped
This event --$4-- is mapped
  • .take: .take will only take the first N values and drain the rest of the values. ex

#bloc #flutter-widget #flutter-state-management #flutter-bloc #flutter

Adobe XD plugin for Flutter with CodePen Tutorial

Recently Adobe XD releases a new version of the plugin that you can use to export designs directly into flutter widgets or screens. Yes, you read it right, now you can make and export your favorite design in Adobe XD and export all the design in the widget form or as a full-screen design, this can save you a lot of time required in designing.

What we will do?
I will make a simple design of a dialogue box with a card design with text over it as shown below. After you complete this exercise you can experiment with the UI. You can make your own components or import UI kits available with the Adobe XD.

#developers #flutter #adobe xd design export to flutter #adobe xd flutter code #adobe xd flutter code generator - plugin #adobe xd flutter plugin #adobe xd flutter plugin tutorial #adobe xd plugins #adobe xd to flutter #adobe xd tutorial #codepen for flutter.

Einar  Hintz

Einar Hintz

1593445800

Flutter Tips: Build a Splash Screen with Flutter BLoC

What is a Splash Screen?

When you open your app on your phone, some apps showing you a logo or a loading bar. That is a splash screen. We can add some actions in splash screen like connection checking, fetch the data, etc.

In this article, I will show you how to build a splash screen using Flutter BLoC state management. I have written some articles about Flutter BLoC. You can read it on these links:

The core concepts of BLoC are Events and States. Simply put, we can call input in BLoC as Events and output as States.


1. Project Setup

Create a new project:

flutter create ftips_bloc_splash

When I’m writing this article, the flutter version I used in this project:

Flutter 1.12.13+hotfix.7 • channel stable • https://github.com/flutter/flutter.git
Framework • revision 9f5ff2306b (4 months ago) • 2020–01–26 22:38:26 -0800
Engine • revision a67792536c
Tools • Dart 2.7.0

Add some dependencies in pubspec.yaml:

name: ftips_bloc_splash
	description: A new Flutter project.

	version: 1.0.0+1

	environment:
	  sdk: ">=2.1.0 <3.0.0"

	dependencies:
	  flutter:
	    sdk: flutter

	  flutter_bloc: ^4.0.0
	  cupertino_icons: ^0.1.2

	dev_dependencies:
	  flutter_test:
	    sdk: flutter

	flutter:
	  uses-material-design: true

flutter_blocis a flutter package that helps implement the BLoC pattern.

and create some folders to store our files, so the structure of the project will be as follows:

Project Structure


2. Setup BLoC

I will write three separate files:

Event

Create a file called splash_event.dart under lib/blocs/splash_bloc. If you have installed a bloc package in vscode, you can simply generate the three bloc files.

part of 'splash_bloc.dart';

	@immutable
	abstract class SplashEvent {}

	class SetSplash extends SplashEvent {}

State

Create a file called splash_bloc.dart under lib/blocs/splash_bloc .

part of 'splash_bloc.dart';

	@immutable
	abstract class SplashState {}

	class SplashInitial extends SplashState {}

	class SplashLoading extends SplashState {}

	class SplashLoaded extends SplashState {}

#bloc #android-app-development #flutter-ui #flutter #flutter-widget #android