关于 ChangeNotifier 提供者

About ChangeNotifier Provider

我正在使用提供程序管理状态,但 ChangeNotifierProvider 不会更改变量的值。 我想在用户注册时显示进度指示器。但是 ChangeNotifierProvider 不给我提供更新值,而是它总是 return 我 _isLoading = false; 我的代码:

AuthServices.dart

class AuthServices with ChangeNotifier {
  bool _isLoading = false;

  bool get loading => _isLoading;

  ///Register User
  Future registerUser(
      {@required String email, @required String password}) async {
    try {
      _isLoading = true;
      notifyListeners();

      await http.post(
          BackEndConfigs.baseUrl +
              BackEndConfigs.version +
              BackEndConfigs.auth +
              EndPoints.register,
          body: {
            "email": email,
            "password": password
          }).then((http.Response response) {
        _isLoading = false;
        notifyListeners();
        return RegisterUser.fromJson(json.decode(response.body));
      });
    } catch (e) {
      print(e);
    }
  }
}

RegisterScreen.dart

class RegisterScreen extends StatefulWidget {
  @override
  _RegisterScreenState createState() => _RegisterScreenState();
}

class _RegisterScreenState extends State<RegisterScreen> {
  AuthServices _authServices = AuthServices();
  ProgressDialog pr;
  @override
  Widget build(BuildContext context) {
    pr = ProgressDialog(context, isDismissible: true);
    // print(status.loading);

    return Scaffold(
      appBar:
          customAppBar(context, title: 'Register Yourself', onPressed: () {}),
      body: _getUI(context),
    );
  }

  Widget _getUI(BuildContext context) {
    return LoadingOverlay(
      isLoading: false,
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 20.0),
        child: SingleChildScrollView(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              VerticalSpace(10.0),
              GreyBoldText('Account Information'),
              VerticalSpace(20.0),
              IconsButtonRow([
                Icon(
                  FontAwesomeIcons.linkedinIn,
                  color: Color(0xff0e76a8),
                ),
                Icon(
                  FontAwesomeIcons.facebook,
                  color: Color(0xff3b5998),
                ),
                Icon(
                  FontAwesomeIcons.google,
                  color: Color(0xff4285F4),
                ),
              ]),
              VerticalSpace(10.0),
              GreyNormalText('or sign up with Email'),
              VerticalSpace(10.0),
              BlackBoldText("Email"),
              AppTextField(
                label: 'Email',
              ),
              BlackBoldText("Password"),
              AppTextField(
                label: 'Password',
              ),
              BlackBoldText("Confirm Password"),
              AppTextField(
                label: 'Confirm Password',
              ),
              VerticalSpace(20.0),
              ChangeNotifierProvider(
                create: (_) => AuthServices(),
                child: Consumer(
                  builder: (context, AuthServices user, _) {
                    return Text(user.loading.toString());
                  },
                ),
              ),
              AppButton(
                  buttonText: 'Next',
                  onPressed: () async {
                    // await pr.show();
                    _registerNewUser();
                  }),
              VerticalSpace(30.0),
              ToggleView(ToggleViewStatus.SignUpScreen),
              VerticalSpace(20.0),
            ],
          ),
        ),
      ),
    );
  }

  _registerNewUser() async {
    _authServices.registerUser(
        email: 'sdjfkldsdf@ssdfdsddfdgsffd.com', password: 'sldjsdfkls');
  }
}

main.dart

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
          scaffoldBackgroundColor: Colors.white,
          hintColor: FrontEndConfigs.hintColor,
          cursorColor: FrontEndConfigs.hintColor,
          fontFamily: 'Gilory'),
      home: RegisterScreen(),
    );
  }
}

您创建了 AuthServices 的两个不同实例。

一个在您的状态开始时 class,一个使用 ChangeNotifierProvider。 调用 _registerNewUser 时,您使用的是在您的州 class 中创建的 AuthServices 而不是提供的

当您在第一个 AuthServices 上调用 registerUser 时,Widget 树中 ChangeNotifierProvider 提供的第二个 AuthServices 的值不会改变。

尝试删除由状态 class 创建的 AuthServices 实例并将您的 ChangeNotifierProvider 向上移动到小部件树,以便您的所有函数共享同一个 AuthServices 实例。