[英]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.