繁体   English   中英

如何在 Flutter 中使用 Provider State 管理通过 API 登录

[英]how to login by API using Provider State management in Flutter

每次我在控制台中收到以下错误时,使用提供程序在 flutter 中使用 Rest API 进行登录/身份验证的正确方法是什么,

  I/flutter (18602): 500
  I/flutter (18602): {"message":"data and hash arguments required"}

这是我的提供商页面:

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class LoginController extends ChangeNotifier{



  bool _isLoading = false;

  bool get isLoading => _isLoading;

 
  
  void loginDemo({
    required String email,
    required dynamic password,
  }) async {
    _isLoading = true;
    notifyListeners();

     String urls = 'https://elated-pink-hedgehog.cyclic.app/login';
     final response = await http.post(Uri.parse(urls),
     body: ({
      "email":email, 
      "password":password
      }));

     if (response.statusCode == 200) {
         print(response.body);
         print('login successfull');
         notifyListeners();
     }else{
      print(response.statusCode);
      print(response.body);
      notifyListeners();

     }
     notifyListeners();

  }

}

这是我在 UI 中调用登录函数的地方:

Consumer<LoginController>(
            builder: (context, value, child) => 
            ElevatedButton(
              onPressed:(){
                if (emailController.text.isEmpty || passwordController.text.isEmpty) {
                  ScaffoldMessenger.of(context).showSnackBar(SnackBar(content:Text('All Field Required')));
                }else{
                  value.loginDemo(
                    email: emailController.text, 
                    password: passwordController.text
                    );
                }
              }, 
              child:Text('login')),
           ),

请帮我解决这个问题。 我是 flutter 和提供者的新手。

我认为错误来自于你发布身体的方式而不是这样做

void loginDemo({
    required String email,
    required dynamic password,
  }) async {
    _isLoading = true;
    notifyListeners();

    final Map<String, dynamic> loginData = {
      'email': email,
      'password': password
    };


     Response response = await post(
      Uri.parse('https://elated-pink-hedgehog.cyclic.app/login'),
      body: json.encode(loginData),
      headers: {'Content-Type': 'application/json'},
    );

     if (response.statusCode == 200) {
         final Map<String, dynamic> responseData = json.decode(response.body);
 //if you have a model class then inject it here
 UserModel authUser = UserModel.fromJson(responseData);
 _isLoading = false;
         notifyListeners();
     }else{
      print(response.statusCode);
      print(response.body);
      notifyListeners();

     }
     notifyListeners();

  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM