api调用成功后flutter返回消息

Posted

技术标签:

【中文标题】api调用成功后flutter返回消息【英文标题】:Flutter return a message after successful Api call 【发布时间】:2020-07-02 01:37:02 【问题描述】:

您好,我是 Flutter 的新手,我决定制作 TodoList 应用程序来提高我的技能并习惯于 Flutter 和使用 api

我想要做的是我想在向 api 提交数据后显示一条用我们的语言编写的消息

代码

Future<Todo> sendData(String title, String body) async
  final http.Response response = await http.post(
    'http://192.168.1.20/Todo_api/public/todos/store',
    headers: <String , String>
      'Content-Type' : 'application/json; charset=UTF-8',
    ,
    body: jsonEncode(<String,String>
      'title' : title,
      'body' : body,
    ),
  );
  if(response.statusCode == 200)
    //200 Created
    //parse json
    return Todo.fromJson(jsonDecode(response.body)) ;
  else
    throw Exception('Failed to submit Contact the Devolopers please ');
  

如您所见,如果代码为 200(成功),我想向用户显示一条消息,而不是解析对用户的 json 响应,因为他不会得到它,而且我想调用 Navigator.pop( ) 以便用户可以返回主屏幕 我尝试了返回函数,小部件,字符串,...等,但它没有工作并一直抛出这个错误

错误:无法返回类型为“Null Function()”的值 函数“sendData”,因为它的返回类型为“Future”。 (return_of_invalid_type at [todolist] lib\CreateTodo.dart:35)

所以我想做之前提到的我想回到主屏幕并像在 laravel 中一样为用户显示友好的消息

return redirect("/")->with('success' , 'Todo Stored Successfully');

就是这样 感谢您查看我的帖子并提前致谢

更新:通过对我的变量执行 if 语句来解决它

完整代码

import 'dart:convert';
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:rflutter_alert/rflutter_alert.dart';
import 'main.dart';
class Todo 
  final title;
  final body;
  Todo (this.title , this.body);

  factory Todo.fromJson(Map<String , dynamic> json)
    return Todo(
      title: json['title'],
      body: json['body'],

    );
  


Future<Todo> sendData(String title, String body) async
  final http.Response response = await http.post(
    'http://192.168.1.20/Todo_api/public/todos/store',
    headers: <String , String>
      'Content-Type' : 'application/json; charset=UTF-8',
    ,
    body: jsonEncode(<String,String>
      'title' : title,
      'body' : body,
    ),
  );
  if(response.statusCode == 201)
    return Todo.fromJson(jsonDecode(response.body));
  else
    return null;
  




class CreateTodo extends StatefulWidget 
  @override
  _CreateTodoState createState() => _CreateTodoState();


class _CreateTodoState extends State<CreateTodo> 
  Future<Todo> _futureTodo;

  String title = "";

  String body = "";

  @override
  Widget build(BuildContext context) 
    return Scaffold(
      appBar: AppBar(
        title: Text("Create Todo"),
      ),
      body: Center(
        child : ListView(
          children: <Widget>[
               Padding(
                padding: const EdgeInsets.all(8.0),
                child: TextField(
                  onChanged: (text)
                    title = text;
                  ,
                  decoration: InputDecoration(hintText: 'Enter Title'),
                ),
              ),
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: TextField(
                onChanged: (text)
                  body = text;
                ,
                decoration: InputDecoration(hintText: 'Enter Body'),
              ),
            ),
            IconButton(
              icon: Icon(Icons.send),
                //if contains data then send else block
                onPressed: () 
                    if (title == '' || body == '')
                      Alert(context: context, title: "Error", desc: "Please fill the form", type: AlertType.error).show();
                    else
                      _futureTodo = sendData(title,body);
                      Alert(context: context, title: "Success", desc: "Stored Successfully", type: AlertType.success,
                          buttons: [
                            DialogButton(
                              child: Text(
                                "Home",
                                style: TextStyle(color: Colors.white, fontSize: 20),
                              ),
                              onPressed: ()
                                Navigator.push(
                                  context,
                                  MaterialPageRoute(builder: (context) => MyApp()),
                                );
                              ,
                              width: 120,
                            ),
                            DialogButton(
                              child: Text(
                                "Back",
                                style: TextStyle(color: Colors.white, fontSize: 20),
                              ),
                              onPressed: ()
                                Navigator.push(
                                  context,
                                  MaterialPageRoute(builder: (context) => CreateTodo()),
                                );
                                ,
                            ),
                          ]
                      ).show();
                    
                ,
            ),
          ],
        ),
      ),
    );
  

【问题讨论】:

【参考方案1】:

这应该对你有帮助

class Api extends StatelessWidget 
  @override
  Widget build(BuildContext context) 
    return Scaffold(
      floatingActionButton: Builder(
        builder: (context)
          return FloatingActionButton(
            onPressed: ()
              sendData("default", "default").then((value)
                Scaffold.of(context).showSnackBar(SnackBar(content: Text("Welcome"),))
              );
            ,
          );
        ,
      ),
    );
  

  Future<bool> sendData(String title, String body) async
    final http.Response response = await http.post(
      'http://192.168.1.20/Todo_api/public/todos/store',
      headers: <String , String>
        'Content-Type' : 'application/json; charset=UTF-8',
      ,
      body: jsonEncode(<String,String>
        'title' : title,
        'body' : body,
      ),
    );
    if(response.statusCode == 200)
      //200 Created
      //parse json
      return true;
    else
      throw Exception('Failed to submit Contact the Devolopers please ');
    
  

【讨论】:

嗯,这对我不起作用,因为主要是你不能在这个函数中返回 bool,而且小吃店也因为某种原因没有出现,但我会接受它作为答案,因为你给了我解决问题的字符串

以上是关于api调用成功后flutter返回消息的主要内容,如果未能解决你的问题,请参考以下文章

阿里云调用 API 服务后返回啥结果

Flutter - 多次调用 API 并使用从互联网返回的更改更新 UI

调用graphql api时Flutter aws放大不返回数据

做一个网站调用外部接口需要数据库嘛

微信支付

在 API 调用 Node express 服务器后显示错误消息