android - 如何在 flutter 中导航到 Post Api 成功响应的其他屏幕

标签 android flutter

在我的 flutter 应用程序中,我必须在 Api 成功响应时导航到其他屏幕。
我的应用程序中有一个登录屏幕,我必须为用户登录调用 Post api 并在该 Api 成功响应时,我想转到其他屏幕
下面是我完成的代码

import 'package:flutter/material.dart';
import 'package:flutter_login_app/screens/login.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(

      ),
      home:  Login(),
    );
  }
}


我的登录类代码

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_login_app/models/LoginApiResponse.dart';
import 'package:flutter_login_app/models/UserLoginModel.dart';
import 'package:flutter_login_app/network/services.dart';
import 'package:flutter_login_app/screens/second_page.dart';

class Login extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return new LoginState();
  }
}

class LoginState extends State<Login> {
  TextEditingController usrNameController = new TextEditingController();
  TextEditingController passController = new TextEditingController();

  @override
  void dispose() {
    // Clean up the controller when the widget is disposed.
    usrNameController.dispose();
    passController.dispose();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return new Scaffold(
        appBar: new AppBar(
          title: Text("Login"),
          centerTitle: true,
        ),
        body: Align(
          alignment: Alignment.center,
          child: new Container(
            child: new ListView(
              children: <Widget>[
                new Container(
                  margin: const EdgeInsets.all(20.0),
                  child: new Column(
                    children: <Widget>[
                      new TextField(
                        controller: usrNameController,
                        decoration: new InputDecoration(
                          hintText: "Enter user  name",
                          border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(5.0)),
                        ),
                      ),
                      new Padding(
                          padding: new EdgeInsets.fromLTRB(0, 20, 0, 0)),
                      new TextField(
                        controller: passController,
                        obscureText: true,
                        decoration: new InputDecoration(
                          hintText: "Enter password",
                          border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(5.0)),
                        ),
                      ),
                      new Padding(
                          padding: new EdgeInsets.fromLTRB(0, 20, 0, 0)),
                      SizedBox(
                          width: double.infinity,
                          height: 55,
                          child: new RaisedButton(
                            onPressed: () {
                              _doLogin(context);
                            },
                            child: new Text("Login"),
                          ))
                    ],
                  ),
                )
              ],
            ),
          ),
        ));
  }

  void _doLogin(BuildContext context) {
    String username = usrNameController.text;
    String password = passController.text;
    User user = new User(User_ID: username, Password: password);
    ApiService apiService = new ApiService();
    print("hello");
     Future<LoginApiResponse>loginresponse = apiService.getLogin("Authenticate", body: user.toMap());
    print("hello");
     FutureBuilder<LoginApiResponse>(
        future: loginresponse,
        builder: (BuildContext context, AsyncSnapshot<LoginApiResponse> snapshot)  {
          print("hello");
          print(snapshot.data.code);
          print(snapshot.data.message);
           navigateToSubPage(context);


        });
  }

  Future navigateToSubPage(context) async {
    Navigator.push(
        context, MaterialPageRoute(builder: (context) => SecondPage()));
  }
}


ApiService类代码

import 'dart:convert';
import 'dart:io';

import 'package:flutter_login_app/models/LoginApiResponse.dart';
import 'package:http/http.dart' as http;

class ApiService{
  String _baseUrl ="http://myloginapi/";


  Future<LoginApiResponse>getLogin(String _methodName, {Map body})async{

           final response = await http.post(_baseUrl + _methodName,body: body);
           //int statusCode = response.statusCode;
           if (response.statusCode == 200) {
             return LoginApiResponse.fromJson(json.decode(response.body));
           }else{
             // If that response was not OK, throw an error.
             throw Exception('Failed to load post');
           }
  }
}


LoginApiResponse 的代码

 class LoginApiResponse {
  String code;
  String message;

  LoginApiResponse({this.code, this.message});

  factory LoginApiResponse.fromJson(Map<String, dynamic>json){
    return LoginApiResponse(
        code : json['Code'],
        message : json['Message']
    );
  }
  Map toMap() {
    var map = new Map<String, dynamic>();
    map["Code"] = code;
    map["Message"] = message;
    return map;
  }
}


谁能告诉我哪里做错了?

最佳答案

据我所知,您的 getLogin 方法是 future 类型。 await 和 async 将处理您 future 的调用,无需 FutureBuilder

 void _doLogin(BuildContext context)async {
            String username = usrNameController.text;
            String password = passController.text;
            User user = new User(User_ID: username, Password: password);
            ApiService apiService = new ApiService();
            print("hello");
             final loginresponse = 
              await apiService.getLogin("Authenticate", body: user.toMap());
           if(loginresponse.responce.statusCode!=200){
           throw Exception("error")
           }
              else { 
              navigateToSubPage(context);
          }
              }

你也需要返回响应

Future<LoginApiResponse>getLogin(String _methodName, {Map body})async{

           final response = await http.post(_baseUrl + _methodName,body: body);
           //int statusCode = response.statusCode;
           if (response.statusCode == 200) {
             return LoginApiResponse.fromJson(json.decode(response.body));
           }else{
             // If that response was not OK, throw an error.
             throw Exception('Failed to load post');
           }
return LoginApiResponse(response);
  }

    class LoginApiResponse {
    final Responce response;
    LoginApiResponse(this.response);
    }

关于android - 如何在 flutter 中导航到 Post Api 成功响应的其他屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59173310/

相关文章:

flutter - 在 Dart 中执行可选(可为空) `Function`

dart - 使用带有 API 调用的 Redux 时如何在 Flutter 中打开下一页

安卓 XML : Set Resource id as View's tag in XML layout file

java - 将标记添加到 HashMap 而不将它们添加到 map

android - keepRunning 设置为 false - 它在 Android 上的真正作用是什么?

java - 如何使一个 ImageView 在按下另一个 ImageView 时消失?

android - 动态改变 Fragment 的容器高度

firebase - Flutter firestore - 检查文档 ID 是否已存在

flutter - 使用 ScrollNotification 滚动出 SliverList 子项时获取该子项的索引

flutter - 如何使用 flutter riverpod statenotifier、ref watch 和 asyncvalue 获取加载状态/微调器?