我有一个名为MyProvider
的变更通知程序。在我的View1
页面中,我调用MyProvider
来显示一个myNumber
变量,该变量是一个数字,我将其初始化为5。
在我的View1
页面上,我有一个按钮,可以将我推到一个也称为MyProvider
的View2
页面。
在我的View2
页面上,我有一个递增myNumber
变量的按钮。
当我使用Navigator.pop返回到View1
页面时,myNumber
变量不会更新。怎么办?
这里的路由器:
case RouterName.kView1:
return CupertinoPageRoute(
builder: (context) => ChangeNotifierProvider<MyProvider>(
create: (BuildContext context) => MyProvider(),
child: Consumer<MyProvider>(builder :(ctx , provider , child){
return View1();
}),
)
);
case RouterName.kView2:
return CupertinoPageRoute(
builder: (context) => ChangeNotifierProvider<MyProvider>(
create: (BuildContext context) => MyProvider(),
child: Consumer<MyProvider>(builder :(ctx , provider , child){
return View2();
}),
)
);
我的myProvider:
class MyProvider with ChangeNotifier {
// Variables
// ---------------------------------------------------------------------------
late int myNumber;
Future? templateDataToLoad;
late LoadingState templateDataState;
// Constructor
// ---------------------------------------------------------------------------
MyProvider(){
_initialise();
}
// Initialisation
// ---------------------------------------------------------------------------
Future _initialise() async
{
templateDataState = LoadingState.isReady;
templateDataToLoad = await loadingData();
notifyListeners();
}
Future loadingData() async
{
myNumber= 5;
templateDataState = LoadingState.isSuccess;
notifyListeners();
}
// Functions public
// ---------------------------------------------------------------------------
void edit()
{
myNumber = 6;
notifyListeners();
}
}
在显示myNumber
的View1
中:
Consumer<MyProvider>(
builder: (context, mymodel, child){
return Text(mymodel.myNumber.toString());
}
),
在View1
中,转到View2:的按钮
Navigator.pushNamed(
context,
RouterName.kView2,
)
在View2
中,我调用了myProvider
中的编辑方法。在我返回View1
之后,但myNumber
的值总是5而不是6。
因为在您的代码中,View1
和View2
的MyProvider
是不同的:
case RouterName.kView1:
return CupertinoPageRoute(
builder: (context) => ChangeNotifierProvider<MyProvider>(
// create a new MyProvider in View1 page
create: (BuildContext context) => MyProvider(),
child: Consumer<MyProvider>(builder :(ctx , provider , child){
return View1();
}),
)
);
case RouterName.kView2:
return CupertinoPageRoute(
builder: (context) => ChangeNotifierProvider<MyProvider>(
// create another MyProvider in View2 page
create: (BuildContext context) => MyProvider(),
child: Consumer<MyProvider>(builder :(ctx , provider , child){
return View2();
}),
)
);
您可以这样定义您的通用MyProvider
:
MyProvider myProvider = MyProvider();
case RouterName.kView1:
return CupertinoPageRoute(
builder: (context) => ChangeNotifierProvider<MyProvider>.value(
value: myProvider,
child: Consumer<MyProvider>(builder :(ctx , provider , child){
return View1();
}),
)
);
case RouterName.kView2:
return CupertinoPageRoute(
builder: (context) => ChangeNotifierProvider<MyProvider>.value(
value: myProvider,
child: Consumer<MyProvider>(builder :(ctx , provider , child){
return View2();
}),
)
);