当前位置:网站首页>Introduction to bloc: detailed explanation of cube

Introduction to bloc: detailed explanation of cube

2022-06-26 02:27:00 Weapon Master 72

background

I learned to write some basic Flutter Development knowledge , However, there is no systematic study on the overall architecture and development mode of the project , After online inquiry , It is found that many projects have adopted Bloc( The business logic component ) This development mode , Here we find the Official website

advantage

Bloc It is easy to separate the presentation layer code from the business logic , This makes your code faster , Easy to test and reusable

Hands on

First of all, for Stream Familiar students can ignore this part ,Java8 There is also a stream part in the new features of .

Starting from scratch

  1. from 0 Start , Write a simple program to know Stream This class creates a new folder :
blocTest
  1. Create a new one test.dart file , Enter the following , Simply understand the following types of flows :
//  Back to a stream , No more than max Number of numbers , it is to be noted that , Every time yield When , Will push data into the stream 
Stream<int> countStream(int max) async* {
    
    for (int i = 0; i < max; i++) {
    
        yield i;
    }
}
//  Use await Wait for every data in the stream , Then return to and , And it's `Future` type 
Future<int> sumStream(Stream<int> stream) async {
    
    int sum = 0;
    await for (int value in stream) {
    
        sum += value;
    }
    return sum;
}

void main() async {
    
  Stream<int> stream = countStream(10);
  int sum = await sumStream(stream);
  print(sum); // 45
}
  1. After preheating , Get started , Installation Library

Create a new file in the root folder pubspec.yaml And enter the following

name: blocTest
environment:
  sdk: ">=2.17.0-0 <3.0.0"
dependencies:
  bloc: ^8.0.0

perform dart pub get Download library

PS C:\Users\XXX\Desktop\blocTest> dart pub get
Resolving dependencies...
Got dependencies!

Get started

This is the picture stolen from the official website :
 Insert picture description here

The state is from Cubit The output of the , Represents part of the application state . You can inform UI Component state , And redraws some parts of itself according to the current state .

  1. Create a Cubit type
//  Defines the state types to be managed , Here to int Example , Complex business can be customized 
class CounterCubit extends Cubit<int> {
    
  //CounterCubit() : super(0);// Specify the initial state as 0
  // You can also externally pass in the initial value :
  CounterCubit(int initialState) : super(initialState);
}
  1. Define a CounterCubit
final cubitA = CounterCubit(0); // state starts at 0
final cubitB = CounterCubit(10); // state starts at 10
  1. The ability to add output states
class CounterCubit extends Cubit<int> {
    
  CounterCubit() : super(0);
  void increment() => emit(state + 1);
  //emit Only in  Cubit  For internal use .state It's the current state 
}
  1. Use
import 'package:bloc/bloc.dart';
void main() {
    
  final cubit = CounterCubit();
  print(cubit.state); // 0
  cubit.increment();
  print(cubit.state); // 1
  cubit.close();
}
  1. subscribe

actually Cubit yes Stream A special type of , Its status can be updated by subscription

void myPrint(int data)  {
    
  print(data);
}

Future<void> main() async {
    
  final cubit = CounterCubit();
  final subscription = cubit.stream.listen(myPrint); // 1
  cubit.increment(); // Output 1
  await Future.delayed(Duration.zero);
  cubit.increment();// Output 2

  await Future.delayed(Duration.zero);
  await subscription.cancel();
  await cubit.close();
}
  1. Observe

You can do it by adding onChange Function to observe Cubit The change of

class CounterCubit extends Cubit<int> {
    
  CounterCubit() : super(0);

  void increment() => emit(state + 1);

  @override
  void onChange(Change<int> change) {
    
    super.onChange(change);
    print(change);
  }
}

modify main function :

void main() {
    
  CounterCubit()
    ..increment()
    ..increment()
    ..close();
}

Output results :

Change {
     currentState: 0, nextState: 1 }
Change {
     currentState: 1, nextState: 2 }

It can be seen that the current status and the next status are output

  1. Use BlocObserver
    Add one by one Observer:
class SimpleBlocObserver extends BlocObserver {
    
  @override
  void onChange(BlocBase bloc, Change change) {
    
    super.onChange(bloc, change);
    print('${
    bloc.runtimeType} $change');
    print(bloc.state);// visit Cuit Instance status 
  }
}

modify main function :

void main() {
    
  BlocOverrides.runZoned(
    () {
    
      CounterCubit()
        ..increment()
        ..close();
    },
    blocObserver: SimpleBlocObserver(),
  );
}

The above code is calling CounterCubit.increment() After that, it will call CounterCubit Of itself onChange and SimpleBlocObserver Of onChange, Actually in BlocObserver You can also access Cubit example (bloc Variable )

  1. Error handling

Change the code again , Man is in increment() Function to call addError Making mistakes , This will call Cubit Of onError Method for error handling

class CounterCubit extends Cubit<int> {
    
  CounterCubit() : super(0);

  void increment() {
    
    addError(Exception('increment error!'), StackTrace.current);
    emit(state + 1);
  }

  @override
  void onChange(Change<int> change) {
    
    super.onChange(change);
    print(change);
  }

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

At this time, an error will be reported

原网站

版权声明
本文为[Weapon Master 72]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/177/202206260050498265.html