我试图发送一个动态口令到用户从Ffltter到Django服务器,它是在下一页发送我必须判断动态口令和返回的结果从API到应用程序在这一部分我写了一个变量"statusCode",这是空的,在POST方法,我说的statuscode=Response.statusCode和在验证按钮,我说,如果statusCode=200,那么转到主屏幕,否则返回一个小吃店,这是我的OTP屏幕代码.在输出中,它返回状态代码200,但在应用程序中,它返回SnackBar,我必须做什么?

import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart';
import 'package:pinput/pinput.dart';
import 'package:whatsapp/Model/ChatModel.dart';
import 'package:whatsapp/Screens/home/HomeScreen.dart';
import 'package:whatsapp/common/utils/utils.dart';
import 'package:whatsapp/constants/colors.dart';
import 'package:whatsapp/utils/theme_manager.dart';

class OTPScreen extends StatefulWidget {
  const OTPScreen(
      {Key? key,
      required this.chatModels,
      required this.sourceChat,
      required this.phoneNumber})
      : super(key: key);
  final List<ChatModel> chatModels;
  final ChatModel sourceChat;
  final String phoneNumber;

  @override
  State<OTPScreen> createState() => _OTPScreenState();
}

class _OTPScreenState extends State<OTPScreen> {
  @override
  Widget build(BuildContext context) {
    Map otp = {};
    int? statusCode;
    bool isLoading = false;
    bool timeOut = false;
    void sendOTP(String otp) async {
      try {
        Response response = await post(
            Uri.parse("https://2858-151-240-216-221.ngrok-free.app/otp-api/"),
            body: {"otp": otp, "phone_number": widget.phoneNumber});
        print(response.body);
        setState(() {
          statusCode = response.statusCode;
        });
      } catch (e) {
        print(e.toString());
      }
    }

    TextEditingController controller = TextEditingController();
    final defaultPinTheme = PinTheme(
      width: 56,
      height: 56,
      textStyle: TextStyle(
          fontSize: 20,
          color: Color.fromRGBO(30, 60, 87, 1),
          fontWeight: FontWeight.w600),
      decoration: BoxDecoration(
        border: Border.all(color: Color.fromRGBO(234, 239, 243, 1)),
        borderRadius: BorderRadius.circular(20),
      ),
    );

    final focusedPinTheme = defaultPinTheme.copyDecorationWith(
      border: Border.all(color: Color.fromRGBO(114, 178, 238, 1)),
      borderRadius: BorderRadius.circular(8),
    );

    final submittedPinTheme = defaultPinTheme.copyWith(
      decoration: defaultPinTheme.decoration?.copyWith(
        color: Color.fromRGBO(234, 239, 243, 1),
      ),
    );

    return Scaffold(
      backgroundColor:
          ThemeManeger().checkIsDark(context) ? primaryColor : Colors.white,
      extendBodyBehindAppBar: true,
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        leading: IconButton(
          onPressed: () {
            Navigator.pop(context);
          },
          icon: Icon(
            Icons.arrow_back_ios_rounded,
            color: ThemeManeger().checkIsDark(context)
                ? Colors.white
                : Colors.black,
          ),
        ),
        elevation: 0,
      ),
      body: Container(
        margin: EdgeInsets.only(left: 25, right: 25),
        alignment: Alignment.center,
        child: SingleChildScrollView(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Image.asset(
                'assets/otp.png',
                width: 150,
                height: 150,
              ),
              SizedBox(
                height: 25,
              ),
              Text(
                "Phone Verification",
                style: TextStyle(
                    fontSize: 22,
                    fontWeight: FontWeight.bold,
                    color: ThemeManeger().checkIsDark(context)
                        ? Colors.white
                        : Colors.black),
              ),
              SizedBox(
                height: 10,
              ),
              Text(
                "We need to register your phone without getting started!",
                style: TextStyle(
                    fontSize: 16,
                    color: ThemeManeger().checkIsDark(context)
                        ? Colors.white
                        : Colors.black),
                textAlign: TextAlign.center,
              ),
              SizedBox(
                height: 30,
              ),
              Pinput(
                length: 6,
                controller: controller,
                showCursor: true,
                onCompleted: (pin) => print(pin),
              ),
              SizedBox(
                height: 20,
              ),
              SizedBox(
                width: double.infinity,
                height: 45,
                child: ElevatedButton(
                  style: ElevatedButton.styleFrom(
                      backgroundColor: tabColor,
                      shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(10))),
                  onPressed: () {
                    sendOTP(controller.text);
                    if (statusCode != null) {
                      if (statusCode == 200) {
                        Navigator.pushReplacement(
                          context,
                          MaterialPageRoute(
                            builder: (builder) => HomeScreen(
                              chatModels: widget.chatModels,
                              sourceChat: widget.sourceChat,
                            ),
                          ),
                        );
                      } else {
                        showSnackBar(context: context, content: "try again");
                      }
                    }
                    else {
                      showSnackBar(context: context, content: "check your connection");
                    }
                  },
                  child: const Text(
                    "Verify Phone Number",
                    style: TextStyle(),
                  ),
                ),
              ),
              Row(
                children: [
                  TextButton(
                      onPressed: () {
                        Navigator.pop(context);
                      },
                      child: Text(
                        "Edit Phone Number ?",
                        style: TextStyle(
                            color: ThemeManeger().checkIsDark(context)
                                ? Colors.white
                                : Colors.black),
                      ))
                ],
              )
            ],
          ),
        ),
      ),
    );
  }
}

推荐答案

您只需在代码中使用asyncawait,以确保它等待来自服务器的响应.更新您的代码,使其在用户按下时的行为如下:

 onPressed: () async {
                 await sendOTP(controller.text);
                    if (statusCode != null) {
                      if (statusCode == 200) {
                        Navigator.pushReplacement(
                          context,
                          MaterialPageRoute(
                            builder: (builder) => HomeScreen(
                              chatModels: widget.chatModels,
                              sourceChat: widget.sourceChat,
                            ),
                          ),
                        );
                      } else {
                        showSnackBar(context: context, content: "try again");
                      }
                    }
                    else {
                      showSnackBar(context: context, content: "check your connection");
                    }
                  },

Flutter相关问答推荐

无法在GroupButton内部正确呈现

在Flutter中,有没有一种方法可以点击页面到后面的页面?

Android Studio将不会构建iOS模拟器应用程序,因为plist.info有问题

为什么Spotify Auth API返回400,而";code_verier不正确?

SingleChildScrollView在ErrorWidget.builder中不工作

在flutter web上渲染多个Youtube视频

如何在Flutter 安全存储器中存储对象值?

抖动问题:检测到0个或2个或更多具有相同值的[DropdownMenuItem]

Flutter-Riverpod:如何只从提供者读取一次值

带有附加图像的ListTile

带有命名参数的回调函数不起作用

Flutter 火焰相机抖动已弃用

以编程方式在 flutter 中安装 apk 时解析错误

无法将Null类型的值分配给 const 构造函数中List类型的参数

如何对齐卡片小部件中的图标按钮?

我怎样才能一次只选中一个复选框?

如何在 flutter 中创建渐变按钮

我正在try 使用 Firebase 在 Flutter 中使用 Google 注销,但它不起作用

如何在 SingleChildScrollView 小部件中管理自定义小部件状态

Flutter:整个判断整个应用生命周期的通用类