使用dio和flutter连接php和mysql

lztngnrs  于 2023-01-02  发布在  Flutter
关注(0)|答案(1)|浏览(179)

我想做的是一个登录界面,但是我想用dio来做。我将在下面分享我的代码。当我用postman测试php部分时,它工作正常,但是我不能用dio发布。当我在调试模式下运行它时,我看不到响应是什么。我没有得到任何错误。如果你能帮助我,我会很高兴
这是我的ILoginService页面

import 'package:dio/dio.dart';

import '../model/login_request_model.dart';
import '../model/login_response_model.dart';

abstract class ILoginService {
  ILoginService(this.dio);

  final String path = "login";

  Future<LoginResponseModel?> fetchLogin(LoginRequestModel loginrequestmodel);
  final Dio dio;
}

这是我的登录服务页面

import 'dart:io';

import 'package:dio/dio.dart';

import '../model/login_request_model.dart';
import '../model/login_response_model.dart';
import 'ILogin_Service.dart';

class LoginService extends ILoginService {
  LoginService(super.dio);

  @override
  Future<LoginResponseModel?> fetchLogin(LoginRequestModel loginrequestmodel) async {
    var formData = FormData.fromMap({'email': loginrequestmodel.email, 'password': loginrequestmodel.password});
    final response = await dio.post(path, data: formData);
    if (response.statusCode == HttpStatus.ok) {
      return LoginResponseModel.fromJson(response.data);
    }
    return null;
  }
}

这是登录视图模型页面

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';

import '../../../../empty_page.dart';
import '../../../../product/user_check/cache_manager.dart';
import '../login.dart';
import '../model/login_request_model.dart';
import '../service/Login_Service.dart.dart';

abstract class LoginViewModel extends State<Login> with CacheManager {
  final GlobalKey<FormState> formKey = GlobalKey();

  final TextEditingController email_controller = TextEditingController();
  final TextEditingController password_controller = TextEditingController();
  late final LoginService loginService;
  final baseUrl = "http://**********/estetik/";

  @override
  void initState() {
    super.initState();
    final dio = Dio(BaseOptions(baseUrl: baseUrl));
    loginService = LoginService(dio);
  }

  Future<void> fetchUserLogin(String email, String password) async {
    final response = await loginService
        .fetchLogin(LoginRequestModel(email: email_controller.text, password: password_controller.text));
    if (response?.token != null) {
      print(response);
      saveToken(response?.token ?? "");
      Navigator.of(context).push(MaterialPageRoute(
        builder: (context) => const Empty(),
      ));
    }
  }
}

这是登录页面

// ignore_for_file: non_constant_identifier_names

import 'package:est/view/auth/login/view_model/login_viewmodel.dart';
import 'package:flutter/material.dart';
import 'package:kartal/kartal.dart';

import '../../../../product/constant/app_text.dart';
import '../../../../product/inputdec/inputdec.dart';
import '../../../../product/padding/page_padding.dart';

class LoginView extends LoginViewModel {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: formKey,
      body: Padding(
        padding: const PagePadding.only(),
        child: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              SizedBox(height: context.dynamicHeight(0.1)),
              Center(child: SizedBox(height: context.dynamicHeight(0.2), child: Image.asset(getLogo))),
              SizedBox(height: context.dynamicHeight(0.15)),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: const [
                  Text(login, style: TextStyle(fontFamily: poppinsbold, fontSize: 24)),
                  Text(emailandpass, style: TextStyle(fontFamily: poppins, fontSize: 15, fontWeight: FontWeight.w500))
                ],
              ),
              SizedBox(height: context.dynamicHeight(0.02)),
              TextFormField(
                controller: email_controller,
                decoration: inputDec(email),
                keyboardType: TextInputType.emailAddress,
              ),
              SizedBox(height: context.dynamicHeight(0.01)),
              TextFormField(
                controller: password_controller,
                decoration: inputDec(password),
                obscureText: true,
              ),
              SizedBox(height: context.dynamicHeight(0.05)),
              const Text(dontacc, style: TextStyle(fontFamily: poppins, decoration: TextDecoration.underline)),
              SizedBox(height: context.dynamicHeight(0.02)),
              SizedBox(
                  height: context.dynamicHeight(0.06),
                  width: context.dynamicWidth(1),
                  child: ElevatedButton(
                      onPressed: () {
                        if (formKey.currentState?.validate() ?? true) {
                          fetchUserLogin(email_controller.toString(), password_controller.toString());
                        }
                      },
                      child: const Text(login)))
            ],
          ),
        ),
      ),
    );
  }

  String get getLogo => "assets/images/ic_logo.png";
}

我没有尝试使用http,我尝试使用dio。我将其作为数据发送,但没有使用formdata,它仍然不起作用

zzlelutf

zzlelutf1#

首先,将fetchUserLogin放在try...catch语句中,这样就可以看到错误消息,如下所示:

try {
  //404
  await dio.get('https://wendux.github.io/xsddddd');
} on DioError catch (e) {
  // The request was made and the server responded with a status code
  // that falls out of the range of 2xx and is also not 304.
  if (e.response != null) {
    print(e.response.data)
    print(e.response.headers)
    print(e.response.requestOptions)
  } else {
    // Something happened in setting up or sending the request that triggered an Error
    print(e.requestOptions)
    print(e.message)
  }
}

相关问题