当前位置:网站首页>Less than 40 lines of code to create a blocprovider
Less than 40 lines of code to create a blocprovider
2022-06-26 12:42:00 【InfoQ】
Preface
SimpleBlocProviderSimpleBlocProvider
Definition
SimpleBlocProviderStatefulWidgetStatefulWidgetStatefulWidget
SimpleBlocProviderbuilderbuilderWidgettypedef StateBuilder<T> = Widget Function(T state);
SimpleBlocProvider<int> (
builder: (count) => Text('$count'),
)
builderSimpleBlocProviderSimpleBlocProviderclass SimpleBlocProvider<T> extends StatefulWidget {
final StateBuilder<T> builder;
final BlocBase<T> bloc;
const SimpleBlocProvider(
{Key? key, required this.builder, required this.bloc})
: super(key: key);
@override
_SimpleBlocProviderState<T> createState() => _SimpleBlocProviderState<T>();
}
BLoC Refresh
StreamStreamlistenStream StreamSubscription<T> listen(void onData(T event)?,
{Function? onError, void onDone()?, bool? cancelOnError});
listenonDatasetState_SimpleBlocProviderState_streamSubscriptionlistendispose_streamSubscription = widget.bloc.stream.listen((data) {
setState(() {
_state = data;
});
});
//
@override
void dispose() {
_streamSubscription.cancel();
super.dispose();
}
_SimpleBlocProviderStatebuildbuilder_state@override
Widget build(BuildContext context) {
return widget.builder(_state);
}
listenSimpleBlocProvider_stateSimpleBlocProviderbuildertypedef StateBuilder<T> = Widget Function(T state);
class SimpleBlocProvider<T> extends StatefulWidget {
final StateBuilder<T> builder;
final BlocBase<T> bloc;
const SimpleBlocProvider(
{Key? key, required this.builder, required this.bloc})
: super(key: key);
@override
_SimpleBlocProviderState<T> createState() => _SimpleBlocProviderState<T>();
}
class _SimpleBlocProviderState<T> extends State<SimpleBlocProvider<T>> {
late T _state;
late StreamSubscription<T> _streamSubscription;
@override
void initState() {
_state = widget.bloc.state;
super.initState();
_streamSubscription = widget.bloc.stream.listen((data) {
setState(() {
_state = data;
});
});
}
@override
Widget build(BuildContext context) {
return widget.builder(_state);
}
@override
void dispose() {
_streamSubscription.cancel();
super.dispose();
}
}
SimpleBlocProvider application
class CounterCubit extends Cubit<int> {
CounterCubit({initial = 0}) : super(initial);
void increment() => emit(state + 1);
void decrement() => emit(state - 1);
@override
void onChange(Change<int> change) {
super.onChange(change);
}
}
class SimpleBlocCounterPage extends StatelessWidget {
final counter = CounterCubit();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Bloc Counter '),
),
body: Center(
child: SimpleBlocProvider<int>(
builder: (count) => Text(
'$count',
style: TextStyle(
fontSize: 32,
color: Colors.blue,
),
),
bloc: counter,
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
counter.increment();
},
tooltip: ' Click to increase ',
child: Icon(Icons.add),
),
);
}
}

GetBuilderPersoneventclass Person {
final String name;
final String gender;
const Person({required this.name, required this.gender});
}
abstract class PersonEvent {}
class UsingCnNameEvent extends PersonEvent {}
class UsingEnNameEvent extends PersonEvent {}
class PersonBloc extends Bloc<PersonEvent, Person> {
PersonBloc(Person person) : super(person) {
on<UsingCnNameEvent>(
(event, emit) => emit(Person(name: ' Ma Nong on the island ', gender: ' male ')));
on<UsingEnNameEvent>(
(event, emit) => emit(Person(name: 'island-coder', gender: 'male')));
}
}
class SimpleBlocCounterPage extends StatelessWidget {
final personBloc = PersonBloc(Person(name: ' Ma Nong on the island ', gender: ' male '));
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Bloc event '),
),
body: Center(
child: SimpleBlocProvider<Person>(
builder: (person) => Text(
' full name :${person.name}, Gender :${person.gender}',
style: TextStyle(
fontSize: 22,
color: Colors.blue,
),
),
bloc: personBloc,
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
personBloc.add(UsingEnNameEvent());
},
tooltip: ' Click to increase ',
child: Icon(Icons.add),
),
);
}
}
summary
SimpleBLocProviderflutter_bloc
边栏推荐
- Typescript learning (I) type
- [probability theory] conditional probability, Bayesian formula, correlation coefficient, central limit theorem, parameter estimation, hypothesis test
- Laravel+gatewayworker completes the im instant messaging and file transfer functions (Chapter 4: server debugging errors)
- 程序员必备,一款让你提高工作效率N倍的神器uTools
- Comparison of latest mobile phone processors in 2020 (with mobile phone CPU ladder diagram)
- Operation analysis and investment prospect research report of China's organic chemical raw material manufacturing industry 2022-2028
- Seven major trends deeply affecting the U.S. consumer goods industry in 2022
- This executeQuery (SQL) cannot compile classes for JSP. What is the reason?
- Oracle锁表查询和解锁方法
- KITTI Detection dataset whose format is letf_top_right_bottom to JDE normalied xc_yc_w_h
猜你喜欢

栈,后入先出

Tiger DAO VC产品正式上线,Seektiger生态的有力补充

Scala-day02- variables and data types

由错误<note: candidate expects 1 argument, 0 provided>引发的思考

International beauty industry giants bet on China

Implementing mixins scheme in applet

Spark-day02-core programming-rdd

Deep thinking from senior member managers
![[probability theory] conditional probability, Bayesian formula, correlation coefficient, central limit theorem, parameter estimation, hypothesis test](/img/2f/f44381ea759f4c1c957a8f9434f0ee.png)
[probability theory] conditional probability, Bayesian formula, correlation coefficient, central limit theorem, parameter estimation, hypothesis test

简易数字电路交通灯设计
随机推荐
I'd like to know what preferential activities are available for stock account opening? Is it safe to open an account online?
PolarisMesh系列文章——概念系列(一)
7-2 数的三次方根
2022 edition of China's medical robot industry investment status investigation and prospect dynamic analysis report
Scala-day03- operators and loop control
What determines the rent
2022 edition of China's cotton chemical fiber printing and dyeing Market Status Investigation and Prospect Forecast Analysis Report
手把手带你学会Odoo OWL组件开发(7):OWL项目实战使用
fastjson的JSONArray和JSONObject[通俗易懂]
PHP laravel+gatewayworker completes im instant messaging and file transfer functions (Chapter 2: explanation of business logic)
TP5 thinkphp5 report serialization of'closure'is not allowed
PHP calculates excel coordinate values, starting with subscript 0
Is it safe to open a securities account in general
What should I do from member labels to portraits?
Spark-day03-core programming RDD operator
A most practical arbitrage wizard EA [2022 modified version]
Scala-day01- companion objects and HelloWorld
How can we reach members more effectively?
做自媒体视频的各种常用工具合集奉上
SQL injection in Pikachu shooting range