对于访问接口,分的细可以分为page(接收访问值并渲染页面)、model(处理数据)、entity(实体类)、api(访问接口)

首先需要创建一个实体,我们快速创建,其中内容为正确返回格式

https://app.quicktype.io/

 

entity已经创建好,那么可以先写model

class RestPasswordViewModel extends BaseModel{
    
  //变量
  String _UserErrorText=null;

  RestPasswordViewModel({@required ApiUtil api}) : super(api: api);

  //方法
  Future<ResetPasswordEntity> reset_password(String username) async {
    setState(ViewState.Busy);
    //api中的方法
    ResetPasswordEntity _resetPassword= await api.resetPassword(username);
    setState(ViewState.Idle);
    return _resetPassword;
  }
  
  //方法
  void checkUserName(String text){
    if(text.isEmpty) {

      _UserErrorText = "This field is required.";
    } else {
      _UserErrorText = null;
    }
    notifyListeners();
  }
  //需要放出去,界面才能使用
  String get userErrorText => _UserErrorText;
}

其中api.resetPassword()还未写,所以需要在api中添加resetPassword方法

  Future<ResetPasswordEntity> resetPassword(String username) async {
    try {
      Map<String, dynamic> map = Map();
      map["userName"] = username;
      dio.options.contentType = "application/json";
      //请求路径AccountApi.resetPassword,参数data
      Response response = await dio.post(AccountApi.resetPassword, data: map);
      //自动封装成entityJSON对象
      ResetPasswordEntity data = ResetPasswordEntity.fromJson(response.data);
      print(data.toJson());//打印
      return data;
    } on DioError catch (err) {
      Log.e(err.message);
      throw err;
    }
  }

 底层已经完成,那么就是在界面上的使用了

class forgot_pwd_View extends StatefulWidget {
  @override
  _forgot_pwd_ViewState createState() => _forgot_pwd_ViewState();
}

class _forgot_pwd_ViewState extends State<forgot_pwd_View> {
  //监听input框
  TextEditingController _userEtControllerName = TextEditingController();
  TextEditingController _userEtController = TextEditingController();
  final LocalAuthenticationService _localAuth =
      locator<LocalAuthenticationService>();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    //设置默认值
     _userEtControllerName =
        new TextEditingController(text: "EFUTT");
    _userEtController = new TextEditingController(text: "abc@123456");
  }

  @override
  Widget build(BuildContext context) {
    return BaseView<RestPasswordViewModel>(
        model: RestPasswordViewModel(api: Provider.of(context)),
        onModelReady: (model) {},
        builder: (context, model, child) {
          return Scaffold(
              resizeToAvoidBottomInset: false,
              body: Stack(
                children: [
                  Container(
                    //背景
                      decoration: BoxDecoration(
                          image:
                               //LoadAssetImage("assets/images/background.png", height: 200.0, width: double.infinity)
                               //  image: Image.asset('assets/images/background.png')
                              DecorationImage(
                        image: ExactAssetImage("assets/images/background.png"),
                        fit: BoxFit.cover,
                      )),

                    padding: const EdgeInsets.only(left: 50.0, right: 50.0),
                      child: Column(
                        children: [

                          SizedBox(
                            height: 150,
                          ),
                          Image.asset(
                            MyImage.login_name,
                          ),

                          SizedBox(
                            height: 50,
                          ),
                          //name
                          Container(
                            margin:
                                const EdgeInsets.only(left: 15.0, right: 15.0),
                            child: TextField(
                              autofocus: false,
                              cursorWidth: 1,
                              style: TextStyle(
                                  fontSize: Dimens.font_sp13,
                                  color: PColor.white_ffffff
                                  ),
                              cursorColor: PColor.black_333333,
                              decoration: InputDecoration(
                                // prefixIcon:Icon(Icons.perm_identity),
                                contentPadding: EdgeInsets.only(top: 15.0),
                                enabledBorder: UnderlineInputBorder(
                                    borderSide: BorderSide(
                                  color: PColor.gray_999999, //边框颜色为绿色
                                  width: 1, //宽度为5
                                )),
                                hintText: "Username",
                                hintStyle: TextStyle(color: PColor.gray_999999),
                                errorText: model.userErrorText,
                                prefixIcon: Padding(
                                    padding: EdgeInsets.all(8),
                                    child: Image.asset(
                                      "assets/images/people_circle.png",
                                      fit: BoxFit.none,
                                    )),
                                focusedBorder: UnderlineInputBorder(
                                    borderSide: BorderSide(
                                  color: PColor.yelow_f08b38, //边框颜色为黄色
                                  width: 1, //宽度为5
                                )),
                                errorBorder: UnderlineInputBorder(
                                  borderSide: BorderSide(
                                    color: PColor.gray_999999, //边线颜色为黄色
                                    width: 1, //边线宽度为2
                                  ),
                                ),
                                focusedErrorBorder: UnderlineInputBorder(
                                    borderSide: BorderSide(
                                  color: PColor.red_fb5858, //边框颜色为绿色
                                  width: 1, //宽度为5
                                )),
                              ),
                              controller: _userEtControllerName,
                            ),
                          ),
                         
                          
                          _btnLoginWidget(model), 
                          // SizedBox(height:15),
                          _localAuthWidget(model), 

                        ],
                      )),
                  Positioned(
                    left: 0,
                    right: 0,
                    bottom: 0,
                    child: Container(
                      margin: const EdgeInsets.only(bottom: 10),
                      alignment: Alignment.center,
                      child: Text('© Kerry Logistics Network Limited.',
                          style: TextStyle(
                              fontSize:ScreenUtil().setSp( Dimens.font_sp12),
                              color: PColor.gray_999999)),
                    ),
                  )
                ],
              ));
        });
  }
Widget _btnLoginWidget(RestPasswordViewModel model) {
    return Container(
      margin: EdgeInsets.only(top:40),
      child: AnimatedButton(
        color: Colors.transparent,
        height: ScreenUtil().setHeight(67),
        width: ScreenUtil().setWidth(271),
        //点击Reset Password按钮
        onPressed: () async{
          //如果输入框中的username为空
          if(_userEtControllerName.text.isEmpty){
            model.checkUserName(_userEtControllerName.text);
          }else{
            try {
              DialogUtils.showLoading(context);
              //请求api => model封装
              ResetPasswordEntity resetPassword = await model.reset_password(_userEtControllerName.text);
              print(resetPassword);
              if (resetPassword.isSuccess == true) {
                DialogUtils.dismissLoading(context);
                CommonUtils.showToast(context, 'Password has been reset, please check your registered mailbox');
                NavigatorUtils.pushAndRemoveUntil(context, loginView());
                print("Password has been reset, please check your registered mailbox");
              } else {
                DialogUtils.dismissLoading(context);
                CommonUtils.showToast(context, resetPassword.errorMessage);
                model.checkUserName(_userEtControllerName.text);
              }
            } catch (e) {
              DialogUtils.dismissLoading(context);
              CommonUtils.showToast(context, DioUtil.parseError(e));
            }
          }
        },
        child: Container(
           child: GestureDetector(
             behavior: HitTestBehavior.opaque,
             child: Text(
              "Reset Password",
              style: TextStyle(
                fontSize: ScreenUtil().setSp(17),
                color: PColor.color_9A9A9A,
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
          width: ScreenUtil().setWidth(200),
          height: ScreenUtil().setHeight(60),
          alignment: Alignment.center,
        ),
      ),
    );
  }
Widget _localAuthWidget(RestPasswordViewModel model) {
    return Container(
      margin: EdgeInsets.only(top:20),
      child: AnimatedButton(
        color: Colors.transparent,
        height: ScreenUtil().setHeight(67),
        width: ScreenUtil().setWidth(271),
         onPressed: () {
           NavigatorUtils.pushAndRemoveUntil(context, loginView());
         },
         child: Container(
           child: GestureDetector(
             behavior: HitTestBehavior.opaque,
              child: Text(
                "Back",
                style: TextStyle(
                  fontSize: ScreenUtil().setSp(17),
                  color: PColor.color_9A9A9A,
                  fontWeight: FontWeight.w500,
                ),
              ),
          ),
          width: ScreenUtil().setWidth(200),
          height: ScreenUtil().setHeight(70),
          alignment: Alignment.center,
        ),
      ),
    );
  }

}

 

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐