BloC - 状态管理 - 红色错误框。
// !!!ОШИБКА ЗДЕСЬ!!!
final ColorBloc _bloc = BlocProvider.of<ColorBloc>(context);
告诉我如何更改此行以使没有错误?接下来是完整代码和有错误的屏幕截图。
主要.dart
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Name App',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
// !!!ОШИБКА ЗДЕСЬ!!!
final ColorBloc _bloc = BlocProvider.of<ColorBloc>(context);
return Scaffold(
appBar: AppBar(
title: Text('Name Page'),
),
body: Stack(
children: [
Align(
alignment: Alignment(0.0, -0.75),
child: BlocBuilder<ColorBloc, Color>(
//cubit: ColorBloc(Colors.red),
builder: (context, state) {
return AnimatedContainer(
width: 150.0,
height: 150.0,
color: state,
duration: Duration(milliseconds: 500),
);
},
),
),
Align(
alignment: Alignment(-1.0, 0.95),
child: Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.start,
children: [
SizedBox(
width: 15.0,
),
Expanded(
flex: 1,
child: Container(
height: 50.0,
child: FlatButton(
onPressed: () { _bloc.add(ColorEvent.event_red); },
splashColor: Colors.blue.withOpacity(0.5),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10)
),
child: Text(
'OK',
style: TextStyle(
color: Colors.white,
fontSize: 20.0,
),
),
color: Colors.red,
),
),
),
SizedBox(
width: 15.0,
),
Expanded(
flex: 1,
child: Container(
height: 50.0,
child: FlatButton(
onPressed: () { _bloc.add(ColorEvent.event_green); },
splashColor: Colors.blue.withOpacity(0.5),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10)
),
child: Text(
'OK',
style: TextStyle(
color: Colors.white,
fontSize: 20.0,
),
),
color: Colors.green,
),
),
),
SizedBox(
width: 15.0,
),
],
),
),
],
),
);
}
}
enum ColorEvent {event_red, event_green}
class ColorBloc extends Bloc<ColorEvent, Color> {
ColorBloc(Color initialState) : super(initialState);
Color _color = Colors.red;
Color get initialState => Colors.red;
@override
Stream<Color> mapEventToState(ColorEvent event) async* {
/*switch(event) {
case ColorEvent.event_red:
_color = Colors.red;
yield _color;
break;
case ColorEvent.event_green:
_color = Colors.green;
yield _color;
break;
}*/
_color = (event == ColorEvent.event_red) ? Colors.red : Colors.green;
yield _color;
}
}
通过调用
BlocProvider.of(context)
,您正在访问不在当前上下文上方的小部件树中的 BlocProvider 小部件。BlocProvider 只是树上某处的一个小部件,它将处理 Bloc 的创建和存储。
只需像这样添加此小部件即可使其工作: