我正在尝试跨页面使用提供程序设置状态。但它没有改变。
我在 main.dart 中添加了 changeNotifierProvider
main.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 路由移动到产品页面。
主页.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'),
),
],)
),
);
}
}
在产品页面中,我使用消费者来获取状态
产品页面.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');
关于Flutter 提供者状态未在消费者小部件中更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58317152/