首页 > 解决方案 > api调用成功后flutter返回消息

问题描述

你好,我是 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() 以便用户可能会返回主屏幕

错误:无法从函数“sendData”返回类型为“Null Function()”的值,因为它的返回类型为“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();
                    }
                },
            ),
          ],
        ),
      ),
    );
  }
}

标签: apiflutterfuture

解决方案


这应该可以帮助你

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 ');
    }
  }
}

推荐阅读