我正在重新编写一个非常简单的应用程序来计算平均值,但是我很难使用BLoC模式。
我的目标是在用户未在TextField中键入成绩时显示AlertDialog。这只能工作一次,但是当我再次尝试时,它什么也没显示。
我该如何解决?
我无法为BLoC构建器分配“未来”,因为它要求我提供小部件。
代码:
import 'package:flutter/material.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../shared/custom_card.dart';
import '../bloc/average_bloc.dart';
class ArithmeticAverageScreen extends StatefulWidget {
@override
_ArithmeticAverageScreenState createState() => _ArithmeticAverageScreenState();
}
class _ArithmeticAverageScreenState extends State<ArithmeticAverageScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('arithmetic_average_title').tr(),
),
body: BlocConsumer<AverageBloc, AverageState>(
listener: (context, state) {
if (state is AverageError) {
return errorDialog(context, state.message);
}
},
builder: (context, state) {
return buildListViewWithCards(context);
},
)
);
}
}
Future errorDialog(BuildContext context, message) {
return showDialog(
context: context,
child: AlertDialog(
title: Text(message)
)
);
}
Widget buildListViewWithCards(BuildContext context) {
TextEditingController _textFieldController = TextEditingController();
return Container(
padding: EdgeInsets.all(20.0),
child: ListView(
children: <Widget>[
CustomCard(
child: Column(
children: <Widget>[
ListTile(
leading: Icon(Icons.help),
title: Text('arithmetic_average_help').tr(),
subtitle: Text('arithmetic_average_help_content').tr(),
)
],
),
),
SizedBox(height: 16.0),
CustomCard(
child: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('arithmetic_average_your_grades', style: Theme.of(context).textTheme.headline5).tr(),
SizedBox(height: 16.0),
Text('arithmetic_average_type_grades', style: Theme.of(context).textTheme.headline6).tr(),
SizedBox(height: 16.0),
Row(
children: <Widget>[
Container(
width: 60.0,
child: TextField(
controller: _textFieldController,
decoration: InputDecoration(
labelText: 'arithmetic_average_textfield_hint'.tr(),
hintText: '5'
),
),
),
SizedBox(width: 16.0),
RaisedButton(
onPressed: () {
submitGrade(context, _textFieldController.text);
},
child: Text('arithmetic_average_add_button').tr(),
color: Colors.teal[300],
textColor: Colors.white,
)
],
)
],
),
)
),
SizedBox(height: 16.0),
CustomCard(
child: Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('arithmetic_average_your_average', style: Theme.of(context).textTheme.headline5).tr(),
SizedBox(height: 16.0),
Center(
child: Text('???', style: Theme.of(context).textTheme.headline4)
)
],
)
)
)
],
)
);
}
void submitGrade(BuildContext context, String average) {
final averageBloc = BlocProvider.of<AverageBloc>(context);
averageBloc.add(GetArithmeticAverage(average));
}