Flutter return 成功 Api 调用后的消息

Flutter return a message after successful Api call

你好,我是 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() 以便用户可以返回主屏幕 我尝试了 return 函数、小部件、字符串等,但它没有用,并不断抛出此错误

error: A value of type 'Null Function() can't be returned from function 'sendData' because it has a return type of 'Future'. (return_of_invalid_type at [todolist] lib\CreateTodo.dart:35)

所以我想像之前提到的那样做,我想返回主屏幕并向用户显示友好消息,如 laravel

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

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

更新:通过对我的变量执行 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();
                    }
                },
            ),
          ],
        ),
      ),
    );
  }
}

这应该对你有帮助

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