当前位置:网站首页>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
- from 0 Start , Write a simple program to know
Stream
This class creates a new folder :
blocTest
- 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
}
- 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 :
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 .
- 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);
}
- Define a CounterCubit
final cubitA = CounterCubit(0); // state starts at 0
final cubitB = CounterCubit(10); // state starts at 10
- 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
}
- Use
import 'package:bloc/bloc.dart';
void main() {
final cubit = CounterCubit();
print(cubit.state); // 0
cubit.increment();
print(cubit.state); // 1
cubit.close();
}
- 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();
}
- 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
- 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 )
- 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
边栏推荐
- 股票开户怎么开户?网上开户是否安全么?
- Scala 基础 (二):变量和数据类型
- 微服务之consul
- CVPR2022 | 长期行动预期的Future Transformer
- 跨平台应用开发进阶(二十三) :一文走近 testflight 上架
- ARM流水线如何提高代码执行效率
- How do I take a screenshot of the iPad? 7 ways to take quick screenshots of iPad
- Eureka注册信息配置备忘
- Breadth first traversal based on adjacency matrix
- Shell learning record (I)
猜你喜欢
【js】免费api判断节假日、工作日和周六日
工作一年闲记
【图像过滤】基于matlab GUI图像过滤系统【含Matlab源码 1913期】
Explain the JVM clearly at one time and don't be asked by the interviewer again
MySQL必須掌握4種語言!
【缺陷检测】基于matlab GUI印刷电路板自动缺陷检测【含Matlab源码 1912期】
Implement decorator pattern for servicecollection
Eureka registration information configuration memo
ARM流水线如何提高代码执行效率
MySQL必须掌握4种语言!
随机推荐
Other codes,, VT,,, K
图的广度优先遍历
@Query difficult and miscellaneous diseases
Convert Weishi camera pictures
二分查找
Redis-SDS
Wechat launched a web version transmission assistant. Is it really easy to use?
How did the thief unlock the password after the iPhone was stolen? After reading the long knowledge
V4l2+qt video optimization strategy
WPF 窗口居中 & 变更触发机制
Cow sequencing problem
网上开户选哪个证券公司?网上开户是否安全么?
Redis Lua沙盒绕过命令执行(CVE-2022-0543)
Calibration...
树莓派 + AWS IoT 入门实验
Breadth first traversal of Graphs
Unexpected output super efficiency SBM model matlab code
SDRAM控制器——添加读写FIFO
Shell learning record (I)
【缺陷检测】基于matlab GUI印刷电路板自动缺陷检测【含Matlab源码 1912期】