问题描述
class HomeView extends StatelessWidget {
/// When user pressed get data button
getData() async {
print("Entering Get Data");
Builder(builder: (context) {
print("Inside the builder");
// ignore: close_sinks
final homeEventReducer = BlocProvider.of<HomeEventReducer>(context);
homeEventReducer.add(DataRequested());
return Center(
child: CircularProgressIndicator(),);
});
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('Home'),),body: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.start,children: <Widget>[
new Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,children: <Widget>[
new RaisedButton(
padding: const EdgeInsets.all(8.0),textColor: Colors.white,color: Colors.pink,onpressed: getData,child: new Text("Get Data"),],);
}
}
这是我的HomeEventReducer
代码的样子-
Stream<HomeState> _reduceDataRequestedEventToState(
DataRequested event) async* {
yield Loading();
try {
final data = await _useCase.getData();
if (data != null) {
yield DataReceivedStatus(message: data);
} else {
yield DataReceivedError(message: "Data Retrieval Error");
}
} catch (error) {
yield DataReceivedError(message: error.message);
}
}
我有2个问题-
-
在我的
HomeView
内,控制流没有进入Builder
内,即我没有得到日志print("Inside the builder");
-
HomeEventReducer中的
DataReceivedStatus
返回我需要在视图中访问的数据。我该怎么办?
我是Flutter的新手。任何帮助将不胜感激?
解决方法
Builder
是一个小部件。当您将其构造函数称为Builder(...
时,您正在创建它的实例。您应该将该实例作为子级交给另一个小部件。你没有那样做。该构建器实例将被浪费,就像下面的代码中的总和将被浪费一样:
1 + 1; // 2 is going to waste
a = 1 + 1; // 2 is not going to waste
我认为您希望在按下按钮时激活构建器。在这种情况下,您的代码可以像这样:
bool isDataRequested = false;
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('Home'),),body: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.start,children: <Widget>[
new Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,children: <Widget>[
isDataRequested != true ? new RaisedButton(
padding: const EdgeInsets.all(8.0),textColor: Colors.white,color: Colors.pink,onPressed:() => setState(() => isDataRequested = true;),child: new Text("Get Data"),) : Builder(
builder: // Place the builder code in here
),],);
}
友善的忠告:“我是Flutter的新手”和“我想使用BLoC”是两个句子,不能很好地融合在一起。我建议使用一种更简单的状态管理方法,直接使用setState()
,至少要等到更好地掌握Flutter为止。