[英]How to manage different States in the same Bloc? Flutter
I am trying to handle 3 different states in my app, in the initState of my home, I call the event "OnInitial" pretending to be a method that fetches data from the local DB.我试图在我的应用程序中处理 3 种不同的状态,在我家的 initState 中,我将事件称为“OnInitial”,假装是一种从本地数据库获取数据的方法。
As you can see in the method on I am setting "6" to the variable "number" as I said, pretending that this would be the data that I brought from the DB.正如您在方法中看到的那样,我将“6”设置为变量“number”,就像我所说的那样,假装这是我从数据库中获取的数据。 My event finishes fetching the data and emits the state "ProductsTercero" already with "the data assigned".我的事件完成获取数据并发出 state“ProductsTercero”已经“分配的数据”。
In my home, if the state is ProductsTercero I paint a column with the "msg" and the "number".在我家,如果 state 是 ProductsTercero,我会用“msg”和“number”绘制一个列。 When inital finishes my screen is redrawn correctly and shows当 inital 完成时,我的屏幕被正确重绘并显示
But my problem is the following.但我的问题如下。 When I press the button called "Tercero" that triggers the event "OnTercero" In my Bloc, when this event is called, it sets a 'New msg' to the variable "msg" of ProducsTercero.当我按下触发事件“OnTercero”的名为“Tercero”的按钮时,在我的 Bloc 中,当调用此事件时,它会将“New msg”设置为 ProducsTercero 的变量“msg”。 What does this?这是做什么的? the next:下一个:
It removes the "number 6" that I had set before, that is, regarding the simulation, I would be deleting all the data that I brought from the DB.它删除了我之前设置的“数字 6”,也就是说,关于模拟,我将删除我从数据库中获取的所有数据。
my expected result was:我的预期结果是:
New msg
6
but i got但我得到了
New msg
0
I debug and it seems like it's always creating a new ProductsThird object. even if I do ProductsTercero().copyWith(msg: 'New msg');我调试它似乎总是在创建一个新的 ProductsThird object。即使我执行 ProductsTercero().copyWith(msg: 'New msg'); is the same.是一样的。
I have worked with only 1 state and this does not happen to me, because I always do a state.copyWith();我只使用过 1 state 而这并没有发生在我身上,因为我总是做一个 state.copyWith(); and the other values of that state are always maintained no matter if i pass 1 attribute of 5 attributes it has.并且无论我是否传递它具有的 5 个属性中的 1 个属性,state 的其他值始终保持不变。 but here, having more than one state and having an abstract state class, I can't write emit(state.copyWith(msg: 'New msg');但是在这里,有一个以上的 state 和一个抽象的 state class,我不能写 emit(state.copyWith(msg: 'New msg');
What am I doing wrong?我究竟做错了什么? What would be the correct way to emit on X state and that this does not happen?在 X state 上发射的正确方法是什么并且不会发生这种情况?
Event, state and bloc code:活动,state和集团代码:
part of 'products_bloc.dart';
@immutable
abstract class ProductsEvent {}
class OnInitial extends ProductsEvent {}
class OnSegundo extends ProductsEvent {}
class OnTercero extends ProductsEvent {}
//**************************************************************//
part of 'products_bloc.dart';
@immutable
abstract class ProductsState {}
class ProductsInitial extends ProductsState {
final String? msg;
final int? numero;
ProductsInitial({numero, msg})
: msg = msg ?? 'MSG: Default Inicial',
numero = numero ?? 0;
ProductsInitial copywith({String? msg, int? numero}) =>
ProductsInitial(msg: msg ?? this.msg, numero: numero ?? this.numero);
}
class ProductsSegundo extends ProductsState {
final String? msg;
final int? numero;
ProductsSegundo({numero, msg})
: msg = msg ?? 'Second: Default Msg',
numero = numero ?? 0;
ProductsSegundo copywith({String? msg, int? numero}) =>
ProductsSegundo(msg: msg ?? this.msg, numero: numero ?? this.numero);
}
class ProductsTercero extends ProductsState {
final String? msg;
final int? numero;
ProductsTercero({numero, msg})
: msg = msg ?? 'Third: Default Msg',
numero = numero ?? 0;
ProductsTercero copywith({String? msg, int? numero}) =>
ProductsTercero(msg: msg ?? this.msg, numero: numero ?? this.numero);
}
//**********************************************************//
import 'package:bloc/bloc.dart';
import 'package:meta/meta.dart';
part 'products_event.dart';
part 'products_state.dart';
class ProductsBloc extends Bloc<ProductsEvent, ProductsState> {
ProductsBloc() : super(ProductsInitial()) {
on<OnInitial>((event, emit) {
emit(ProductsInitial().copywith(
msg: 'Initial msg'
));
emit(ProductsTercero(numero: 6));
});
on<OnSegundo>((event, emit) {
emit(ProductsSegundo());
});
on<OnTercero>((event, emit) {
emit(ProductsTercero(msg: 'New msg'));
});
}
}
Homepage code:首页代码:
import 'package:bloc_test/src/bloc/products/products_bloc.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
@override
void initState() {
BlocProvider.of<ProductsBloc>(context).add(OnInitial());
super.initState();
}
@override
Widget build(BuildContext context) {
return BlocBuilder<ProductsBloc, ProductsState>(
builder: (context, state) {
return Scaffold(
body: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
(state is ProductsInitial) ? Column(
children: [
Center(child: Text(state.msg!)),
Center(child: Text(state.numero!.toString())),
],
)
: (state is ProductsSegundo) ? Column(
children: [
Center(child: Text(state.msg!)),
Center(child: Text(state.numero!.toString())),
],
)
: (state is ProductsTercero) ? Column(
children: [
Center(child: Text(state.msg!)),
Center(child: Text(state.numero!.toString())),
],
)
: Center(child: Text('Nada')),
SizedBox(
height: 40,
width: double.infinity,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
ElevatedButton(
onPressed: () {
BlocProvider.of<ProductsBloc>(context).add(OnInitial());
},
child: Text('Initial')),
ElevatedButton(
onPressed: () {
BlocProvider.of<ProductsBloc>(context).add(OnSegundo());
},
child: Text('Segundo')),
ElevatedButton(
onPressed: () {
BlocProvider.of<ProductsBloc>(context).add(OnTercero());
},
child: Text('Tercero'))
],
),
),
],
),
);
},
);
}
}
You are not passing num value on emit(ProductsTercero(msg: 'New msg'));
您没有在emit(ProductsTercero(msg: 'New msg'));
上传递 num 值emit(ProductsTercero(msg: 'New msg'));
Since num == null then it is set to 0, as defined by your code.由于 num == null 那么它被设置为 0,如您的代码所定义。
Try Replacing like below尝试更换如下
on<OnTercero>((event, emit) {
emit(ProductsTercero(msg: 'New msg',numero: 6));
});
You are creating a new state object with each event.您正在为每个事件创建一个新的 state object。 You want to copy the existing state.您要复制现有的 state。
on<OnTercero>((event, emit) {
emit(state.copyWith(msg: 'New msg'));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.