当前位置: 首页 > 工具软件 > bloc > 使用案例 >

BLOC

魏书
2023-12-01
我犯下的错误:
用inheritedwidget包裹了需要共享数据的控件之后,却掉了参数,这里面是需要注明共享数据类的;
如:

import 'package:flutter/material.dart';
import 'counter_bloc_demo.dart';

void main()=>runApp(MyApp());

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}

class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
return CounterProvider(
bloc: CounterBloc(),
child: Scaffold(
body: CounterHome(),
floatingActionButton: CounterActionButton(),
),
);
}
}




import 'package:flutter/material.dart';
import 'dart:async';

class CounterHome extends StatelessWidget {
@override
Widget build(BuildContext context) {
CounterBloc _counterBloc = CounterProvider.of(context).bloc;
return Center(
child: StreamBuilder(
initialData: 0,
stream: _counterBloc.count,
builder: (context,snapshot){
return ActionChip(
label:Text('${snapshot.data}'),
onPressed: (){
_counterBloc.log('I am ActionChip !');
_counterBloc.counter.add(2);
});
},
),
);
}
}

class CounterActionButton extends StatelessWidget {
@override
Widget build(BuildContext context) {
CounterBloc _counterBloc = CounterProvider.of(context).bloc;
return FloatingActionButton(
child: Icon(Icons.add),
onPressed:(){
_counterBloc.log('I love you !');
_counterBloc.counter.add(1);
} ,
);
}
}

//共享数据类:这个类里面都是共享数据和共享方法;
class CounterBloc{
int _count = 0;
final _counterActionController = StreamController<int>();
final _counterController = StreamController<int>();
StreamSink<int> get counter => _counterActionController.sink;//不理解这句话的get
Stream<int> get count=>_counterController.stream;
CounterBloc(){
_counterActionController.stream.listen(onData);
}
onData(int data){
print('$data');
_count=data+_count;
_counterController.add(_count);
}
void dispose(){
_counterActionController.close();
_counterController.close();
}
void log(data){print(data);}
}

class CounterProvider extends InheritedWidget {
final Widget child;//要共享的组件;
final CounterBloc bloc;//要共享的数据;

CounterProvider({
this.bloc,
this.child,
}) :super(child: child);

//定义一个便捷方法,方便子树中的widget获取共享数据
static CounterProvider of(BuildContext context) {
return context.inheritFromWidgetOfExactType(CounterProvider);
}

//该回调决定当data发生变化时,是否通知子树中依赖data的Widget
@override
bool updateShouldNotify(CounterProvider old) {
//如果返回true,则子树中依赖(build函数中有调用)本widget
//的子widget的`state.didChangeDependencies`会被调用
return old.bloc != bloc;
}
}








转载于:https://www.cnblogs.com/braveheart007/p/10828761.html

 类似资料: