【问题标题】:Flutter/Dart: How to make a Boolean Listenable with the ChangeNotifierProvider?Flutter/Dart:如何使用 ChangeNotifierProvider 使布尔值可听?
【发布时间】:2020-11-04 02:19:06
【问题描述】:

我正在使用 ChangeNotifierProvider 提供一个布尔值,该布尔值根据用户是否登录返回真或假。如何使布尔值可侦听,以便提供者在用户登录/退出时自动更新它?

Widget build(BuildContext context) {
var socialProvider = Provider.of<SocialProvider>(context);
return Container(  
           child: new FlatButton(
           onPressed: () {
               if (
                  socialProvider.currentlogged != true
                  ) {                        
       Do something
             } else {
        Do something else
                      },
),}

【问题讨论】:

    标签: flutter dart boolean provider changenotifier


    【解决方案1】:

    使用提供者实现身份验证功能的最佳方法是使用提供者包装您的父类。例如,

    MultiProvider(
        providers: [
          ChangeNotifierProvider(
            create: (_) => Authentication(),
          ),
          )
        ],
        child: MaterialApp(
              ........
        ),
    

    通过这种方式,您可以在应用程序的任何位置使用提供程序,只需使用 Consumer 包装子小部件。

    Consumer<Authentication>(
          builder: (context, auth, _) => Container(  
           child: new FlatButton(
           onPressed: () {
               if (auth.currentlogged != true) {                        
                 Do something
             } else { 
                 Do something else
             }
    

    由于身份验证控制整个应用程序本身,我将 MaterialApp 与 Provider 包装在一起,您可以在任何小部件中执行此操作,以便其所有子级都可以使用它。 当你调用 notifyListeners();在提供者中,它将重新呈现整个消费者部分。

    【讨论】:

    • 谢谢,太完美了! :)
    猜你喜欢
    • 2020-11-20
    • 1970-01-01
    • 2020-06-24
    • 2019-12-03
    • 2020-12-23
    • 2020-07-24
    • 2021-06-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多