Flutter使用上一页上的提供程序更新值



我有一个名为MyProvider变更通知程序。在我的View1页面中,我调用MyProvider来显示一个myNumber变量,该变量是一个数字,我将其初始化为5。

在我的View1页面上,我有一个按钮,可以将我推到一个也称为MyProviderView2页面。

在我的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();
}

}

在显示myNumberView1中:

Consumer<MyProvider>(
builder: (context, mymodel, child){
return Text(mymodel.myNumber.toString());
}
),

View1中,转到View2:的按钮

Navigator.pushNamed(
context,
RouterName.kView2,
)

View2中,我调用了myProvider中的编辑方法。在我返回View1之后,但myNumber的值总是5而不是6。

因为在您的代码中,View1View2MyProvider是不同的:

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();
}),
)
);

相关内容

  • 没有找到相关文章

最新更新