flutter 获取登录后的返回值,并更新到页面

325 阅读1分钟

1、环境

1)使用drawer页面作为点击登录

2)点击登录后弹出登录框,认证成功后返回用户数据

3)drawer页面更新 具体流程如下图:

image.png

2、实现方式 1)定义返回参数:

class UserInfoArg {
  String nickName = '';
  String userId = '';
  String avatarPath = '';
  UserInfoArg(this.nickName, this.userId, this.avatarPath);
}

2)drawer页面定义UserInfoArg,并使用路由弹出登录框


static UserInfoArg _userArg = UserInfoArg('', '', '');

SizedBox(
  width: 50.0,
  height: 50.0,
  child: CircleAvatar(
    child: IconButton(
      onPressed: () { // 弹出登录页面
        Navigator.of(context).pushNamed("/login").then((value) {
          setState(() { // 获取结果后,使用setState更新页面
            _userArg = value as UserInfoArg;
          });
        });
      },
      icon: Icon(Icons.home),
    ),
  ),
),


Align(
  alignment: Alignment.centerLeft,
  child: Text(
    _userArg.nickName.isEmpty ? '点击头像登录' : _userArg.nickName,
    style: TextStyle(fontSize: 16, fontWeight: FontWeight.w700),
  ),
),

3)login页面代码

void _onLogin() async {
  if ((_formKey.currentState as FormState).validate()) {
    var result;
    try {
      result = await DioHttp.login({
        "username": _unameController.text,
        "password": _pwdController.text,
      });
      if (result['error'] == 0) {
        Navigator.of(context).pop(
          UserInfoArg(
            result['userInfo']['nickName'],
            result['userInfo']['uid'].toString(),
            result['userInfo']['avatar']
          )
        );
      } else {
        this._showInfo(result['des']);
      }
    } on DioError catch(e) {
      this._showInfo(e.toString());
    }
  }
}