我正在重新编写一个非常简单的应用程序来计算平均值,但是使用Provider程序包却很难。我想将业务逻辑从负责小部件创建的文件中移出。我想使用提供程序包。
好的,我有负责构建布局的文件,但是我想听听TextField小部件中的更改。我如何有效地做到这一点?我有另一个文件,它是提供程序类,它将侦听此TextField小部件上的更改。但是,我不想在main.dart文件中创建ChangeNotifierProvider,因为我想要一个本地状态。我想将TextField的值传递给提供程序类。
import 'package:flutter/material.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:provider/provider.dart';
import '../providers/arithmetic_average.dart';
class ArithmeticAverageScreen extends StatefulWidget {
@override
_ArithmeticAverageScreenState createState() => _ArithmeticAverageScreenState();
}
class _ArithmeticAverageScreenState extends State<ArithmeticAverageScreen> {
final _textFieldController = TextEditingController();
var _grades = List<Widget>();
@override
void dispose() {
_textFieldController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (context) => ArithmeticAverageProvider(),
child: Scaffold(
appBar: AppBar(
title: Text('arithmetic_average_title').tr(),
),
body: Container(
padding: EdgeInsets.all(16.0),
child: ListView(
children: <Widget>[
Card(
child: Container(
padding: EdgeInsets.symmetric(vertical: 20.0),
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
ListTile(
leading: Icon(Icons.help),
title: Text('arithmetic_average_help').tr(),
subtitle: Text('arithmetic_average_help_content').tr(),
)
],
),
)
),
SizedBox(height: 16.0),
Card(
child: Container(
padding: EdgeInsets.symmetric(vertical: 20.0, horizontal: 20.0),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Text('arithmetic_average_your_grades', style: Theme.of(context).textTheme.headline5).tr(),
SizedBox(height: 16.0),
Text('arithmetic_average_grades_one_at_a_time', style: Theme.of(context).textTheme.headline6,).tr(),
SizedBox(height: 16.0),
Row(
children: <Widget>[
Container(
width: 60.0,
child: TextField(
controller: _textFieldController,
keyboardType: TextInputType.numberWithOptions(
decimal: true
),
decoration: InputDecoration(
hintText: '5',
labelText: 'arithmetic_average_grade'.tr()
),
),
),
SizedBox(width: 20.0,),
RaisedButton(
onPressed: () {
},
color: Colors.teal[300],
textColor: Colors.white,
child: Text('arithmetic_average_add_button').tr(),
),
],
),
SizedBox(height: 16.0,),
Wrap(
children: _grades,
),
],
),
),
)
],
),
)
),
);
}
}
import 'package:flutter/material.dart';
class ArithmeticAverageProvider extends ChangeNotifier {
}
答案 0 :(得分:0)
TextField“ onChange”应该在“ ArithmeticAverageProvider()”中调用一个方法,该方法将调用“ NotifyListeners()”。