我正在尝试使用跨页面的提供者来设置状态。但它没有改变。
我已经在main.dart中添加了changeNotifierProvidermain.dart
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(builder: (context) => GlobalState())
],
child: MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
routes: {
'/': (context) => HomePage(),
'/products': (context) => ProductsPage()
}
)
);
}
}
我正在尝试设置并获取简单的名称字符串
globatState.dart
class GlobalState extends ChangeNotifier{
String _name = 'Hello';
String get getName => _name;
void setName(String value){
_name = value;
notifyListeners();
}
}
在主页中,我正在设置状态,并且可以使用导航器pushNamed路线移至产品页面。
homepage.dart
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context){
GlobalState gs = GlobalState();
return Scaffold(
appBar: AppBar(title: Text('Home'),),
body: Container(
child: Column(children: <Widget>[
RaisedButton(onPressed: ((){
gs.setName('World');
}),
child: Text('Set data'),
),
RaisedButton(
onPressed: () => Navigator.pushNamed(context, '/products'),
child: Text('Products'),
),
],)
),
);
}
}
在产品页面中,我正在使用消费者获取状态productsPage.dart
class ProductsPage extends StatelessWidget{
@override
Widget build(BuildContext context){
return Scaffold(appBar: AppBar(title: Text('Products'),
),
body: Container(child:Column(children: <Widget>[
Text('This is the productPage'),
Container(
child:Consumer<GlobalState>(
builder: (context, gs, child){
return Text('this is the data: ${gs.getName}');
},
)
)
],))
);
}
}
但是在产品页面中,我仅获得状态的初始值,而不是更改后的状态的初始值。我错过了什么还是导航方式错误?
GlobalState gs = GlobalState();
将创建您的GlobalState类的新实例。未注册为提供者。
相反,使用提供者提供的实例是这样的>
GlobalState gs = Provider.of<GlobalState>(context, listen:false);
gs.setName('world');