【发布时间】:2019-10-10 06:58:30
【问题描述】:
我正在尝试使用提供程序跨页面设置状态。但它没有改变。
我在 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'),
),
],)
),
);
}
}
在产品页面中,我使用消费者来获取状态 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}');
},
)
)
],))
);
}
}
但在产品页面中,我只获得状态的初始值,而不是更改后的状态。是我遗漏了什么还是我导航错误?
【问题讨论】:
-
首页第4行,改用Provider.of
-
使用 Provider.of 为我工作。
标签: flutter