提供者不刷新吗?

时间:2019-08-12 07:46:42

标签: flutter flutter-provider

我的UserProvider没有按预期刷新。

当我在Setter的FistName上打印一个值时,我的最后一个值是“ test”,但在我的小部件中我只会得到“”。

UserProvider

class UserProvider with ChangeNotifier {
  String _email = '';
  String _firstName = '';
  String _lastName = '';
  String _id = '';

  int tokenExpireIn = 0;

  SharedPreferences prefs;

  String get token {
    return prefs.getString('userToken');
  }
  set token(String token) {
    prefs.setString('userToken', token);
    notifyListeners();
  }


  String get email => _email;
  set email(String email) {
    _email = email;
    notifyListeners();
  }

  String get firstName => _firstName;
  set firstName(String firstName) {
    _firstName = firstName;
    notifyListeners();
  }

  String get lastName => _lastName;
  set lastName(String lastName) {
    _lastName = lastName;
    notifyListeners();
  }

  String get id => _id;
  set id(String id) {
    _id = id;
    notifyListeners();
  }

  Future<bool> register(
      {@required String email,
      @required String password,
      @required String firstName,
      @required String lastName}) async {
    final response = await http.post(
      ServerSettings.registerUrl,
      body: json.encode(
        {
          'email': email,
          'password': password,
          'firstName': firstName,
          'lastName': lastName,
        },
      ),
      headers: {'Content-Type': 'application/json'},
    );
    return json.decode(response.body)['success'];
  }

  Future<bool> login(
      {@required String email, @required String password}) async {
    final response = await http.post(
      ServerSettings.loginUrl,
      body: json.encode(
        {
          'email': email,
          'password': password,
        },
      ),
      headers: {'Content-Type': 'application/json'},
    );
    if (json.decode(response.body)['success']) {
      await setUserInfo(json.decode(response.body));
      return true;
    } else {
      await resetUserInfo(true);
      return false;
    }
  }

  Future<bool> isLogged() async {
    prefs ??= await SharedPreferences.getInstance();

    final response = await http.get(
      ServerSettings.checkUserUrl,
      headers: {
        'Content-Type': 'application/json',
        'authorization': 'Bearer $token'
      },
    );
    final bool rtn = response.statusCode == 200;
    return rtn;
  }

  Future<void> getUserInfo() async {
    prefs ??= await SharedPreferences.getInstance();
    final response = await http.get(
      ServerSettings.userInfo,
      headers: {
        'Content-Type': 'application/json',
        'authorization': 'Bearer $token'
      },
    );
    if (json.decode(response.body)['success']) {
      print(json.decode(response.body));
      await setUserInfo(json.decode(response.body));
    } else {
      resetUserInfo(true);
    }
  }

  Future setUserInfo(dynamic body) async {
    await resetUserInfo(false);
    final user = body['user'];
    email = user['email'];
    firstName = user['firstName'];
    lastName = user['lastName'];
    id = user['userID'];
    tokenExpireIn = user['expiresIn'];
    if(user['token']!=null){
      token = user['token'];
    }
  }

  Future resetUserInfo(bool resetToken) async {
    email = '';
    firstName = '';
    lastName = '';
    id = '';
    tokenExpireIn = 0;
    if(resetToken)
    token = '';
  }
}

ProtectedWidget


  ProtectedWidget({@required this.child});

  @override
  _ProtectedWidgetState createState() => _ProtectedWidgetState(child: child);
}

class _ProtectedWidgetState extends State<ProtectedWidget> with AfterInitMixin<ProtectedWidget>{
  Widget child;
  _ProtectedWidgetState({@required this.child});

  bool isLoading;

  @override
  Widget build(BuildContext context) {
    return isLoading
        ? Scaffold(body: Center(child: CircularProgressIndicator()))
        : child;
  }

  @override
  void didInitState() {
    final UserProvider userProvider = Provider.of<UserProvider>(context);
    setState(() {
      isLoading = true;
    });
    userProvider.isLogged().then((value) {
      if (!value) {
        Navigator.pushReplacementNamed(context, '/login');
      } else {
        setState(() {
          userProvider.getUserInfo();
          isLoading = false;
        });
      }
    });
  }
}

主页

 @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {

  @override
  Widget build(BuildContext context) {
    final UserProvider userProvider = Provider.of<UserProvider>(context);
    return ProtectedWidget(
      child: Scaffold(
        body: Center(
          child: Container(
            padding: EdgeInsets.all(50),
            alignment: Alignment.center,
            child:
              Column(mainAxisAlignment: MainAxisAlignment.center, children: [
              Text('Home'),
              Text('firstName ' + userProvider.firstName),
            ]),
          ),
        ),
      ),
    );
  }
}

在我的HomeScreen中,我仅获得“ FirstName”,但我期望“ FirstName test” 因为提供者中FirstName的最后一个值是“ test”。

我在做什么错了?

编辑

我将主屏幕更改为

lass HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return ProtectedWidget(
        child: Consumer(
      builder: (context, UserProvider userProvider, _) => Scaffold(
        body: Center(
          child: Container(
            padding: EdgeInsets.all(50),
            alignment: Alignment.center,
            child:
                Column(mainAxisAlignment: MainAxisAlignment.center, children: [
              Text('Home'),
              Text('firstName ' + userProvider.firstName),
            ]),
          ),
        ),
      ),
    ));
  }
}

只需添加一个Consumer小部件,这是一个好的解决方案吗?

0 个答案:

没有答案