[英]How can I Initialize provider?
我已经在我的应用程序中实现了用于状态管理的 Provider。 现在,我需要在加载屏幕后在类中添加一些数据。
我怎么能做到这一点?
stepInfo.addToList = new VaccStep(); // Need to call it one time once screen is loaded.
我试图从 initState 调用这个方法,但它给出了错误!!
class AdminAddVaccination extends StatefulWidget {
@override
State createState() => new AdminAddVaccinationState();
}
class AdminAddVaccinationState extends State<AdminAddVaccination> {
@override
void initState() {
super.initState();
var stepInfo = Provider.of<StepInfo>(context); // ERROR!!
stepInfo.addToList = new VaccStep(); // ERROR!!
}
Widget build(BuildContext context) {
return new ChangeNotifierProvider(
builder: (context) => StepInfo(),
child: ScreenBody(),
);
}
}
class ScreenBody extends StatelessWidget {
@override
Widget build(BuildContext context) {
var stepInfo = Provider.of<StepInfo>(context);
return new Scaffold(
resizeToAvoidBottomPadding: false,
key: stepInfo.scaffoldKey,
body: new GestureDetector(
onTap: () {
FocusScope.of(context).requestFocus(new FocusNode());
},
child: new SafeArea(
top: true,
bottom: false,
child: new Stack(children: <Widget>[
new Opacity(
opacity: 0.04,
child: new Image.asset(
"assets/userProfile/heartBeat.png",
fit: BoxFit.cover,
height: 250.0,
),
),
new Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
new Container(
color: primaryGreen,
width: double.infinity,
height: 65.0,
child: new Stack(
children: <Widget>[
new Align(
alignment: Alignment.center,
child: stepInfo.loading
? JumpingText('......')
: new Container()),
new Align(
alignment: Alignment.centerLeft,
child: new Padding(
padding: EdgeInsets.only(top: 5.0, left: 20.0),
child: new InkWell(
child: new Container(
child: Icon(
Icons.arrow_back,
color: Colors.white,
size: 30.0,
),
),
onTap: () {
Navigator.pop(context);
},
),
),
),
],
),
),
new Padding(
padding: EdgeInsets.only(top: 0.0),
child: new Material(
elevation: 1.0,
color: Colors.transparent,
child: new Container(
color: borderColor,
width: double.infinity,
height: 5.0,
),
),
),
VaccName(),
],
),
ItemListing(),
AddStep(),
]),
)));
}
}
错误!! flutter: 以下 ProviderNotFoundError 被抛出 building Builder: flutter: Error: 无法在此 AdminAddVaccination Widget 上方找到正确的 Provider * 为 Provider flutter 提供类型: * 为 Consumer flutter 提供类型: * 为 Provider.of() flutter 提供类型: * 始终使用包导入。 例如:`import 'package:my_app/my_code.dart';
只需在您的提供者中添加一个构造函数:
class StepInfo extends ChangeNotifier {
StepInfo() {
this.addToList = new VaccStep();
}
[...]
}
更改AdminAddVaccination类中的initState()和build()方法,如下所示:
var stepInfo;
@override
void initState() {
super.initState();
stepInfo = new StepInfo();
stepInfo.addToList = new VaccStep();
}
@override
Widget build(BuildContext context) {
return new ChangeNotifierProvider<StepInfo>(
builder: (context) => stepInfo,
child: ScreenBody(),
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.