【问题标题】:Flutter - MultiProvider (ChangeNotifierProvider) doesn't workFlutter - MultiProvider(ChangeNotifierProvider)不起作用
【发布时间】:2020-09-21 00:02:39
【问题描述】:

ChangeNotifierProvider 不起作用!我不知道是什么问题。 谁能告诉我这段代码有什么问题? 谢谢你

我想将 test 值传递到下一页。

这里是主要功能和提供者

void main() {
runApp(
MultiProvider(
providers:[
ChangeNotifierProvider<ProductsNotifier>(create:(context)=> ProductsNotifier()),
//  second provider...
],
child:MaterialApp( home: MyApp())
)  
);
}

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
//Provider
return Scaffold(
  appBar: AppBar(
    title: Text('Test'),
  ),
  body: Container(
    child:RaisedButton(
    onPressed: (){
    ProductsNotifier obj = new ProductsNotifier();
    obj.testFun();
      Navigator.push(context,
            MaterialPageRoute(builder: (context) => NextPage()),
        );
      },
      child: Text('GO TO THE NEXT PAGE'),
    )
   ),
  );
 }
}

下一页:

class NextPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
 var txt = Provider.of<ProductsNotifier>(context);

return Scaffold(
  appBar: AppBar(
    title: Text('Next Page'),
  ),
  body: Container(
    child: Text(txt.test.toString()),
  ),
);
}
}

类 ProductsNotifier

class ProductsNotifier with ChangeNotifier{
String _test ;
String get test => _test;

 void testFun()  {
 _test = "DONE!";
  notifyListeners();
 }
}

【问题讨论】:

    标签: flutter provider flutter-change-notifier


    【解决方案1】:

    首先删除这一行:

    ProductsNotifier obj = new ProductsNotifier();
    

    这里已经创建好了:

    ChangeNotifierProvider<ProductsNotifier>(create:(context)=> ProductsNotifier()),
    

    然后

    class ProductsNotifier with ChangeNotifier{
    

    替换为:

    class ProductsNotifier extends ChangeNotifier{
    

    【讨论】:

    • 啊哈,谢谢,我是 Flutter 新手,所以不太了解。现在我知道了。再次感谢您。
    猜你喜欢
    • 2022-01-25
    • 2021-06-06
    • 2021-03-27
    • 1970-01-01
    • 2020-11-20
    • 1970-01-01
    • 1970-01-01
    • 2021-01-15
    • 2020-12-23
    相关资源
    最近更新 更多