簡體   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