Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/flutter/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
颤振在成功调用Api后返回消息_Api_Flutter_Future - Fatal编程技术网

颤振在成功调用Api后返回消息

颤振在成功调用Api后返回消息,api,flutter,future,Api,Flutter,Future,您好,我是新来的颤振,我决定使TodoList应用程序,以提高我的技能,并习惯颤振和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',

您好,我是新来的颤振,我决定使TodoList应用程序,以提高我的技能,并习惯颤振和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 ');
  }
}
就这样 感谢您查看我的帖子,并提前表示感谢

更新:通过对我的变量执行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();
                    }
                },
            ),
          ],
        ),
      ),
    );
  }
}
导入'dart:convert';
导入“dart:async”;
进口“包装:颤振/材料.省道”;
将“package:http/http.dart”导入为http;
导入“package:rflutter_alert/rflutter_alert.dart”;
导入“main.dart”;
待办事项{
最终标题;
最终机构;
Todo({this.title,this.body});
工厂Todo.fromJson(映射json){
返回待办事项(
标题:json['title'],
body:json['body'],
);
}
}
Future sendData(字符串标题、字符串正文)异步{
final http.Response Response=wait http.post(
'http://192.168.1.20/Todo_api/public/todos/store',
标题:{
“内容类型”:“应用程序/json;字符集=UTF-8”,
},
正文:JSONECODE({
“标题”:标题,
“身体”:身体,
}),
);
如果(response.statusCode==201){
返回Todo.fromJson(jsonDecode(response.body));
}否则{
返回null;
}
}
类CreateTodo扩展StatefulWidget{
@凌驾
_CreateTodoState createState()=>\u CreateTodoState();
}
类_createToState扩展状态{
未来(Future);
字符串标题=”;
字符串体=”;
@凌驾
小部件构建(构建上下文){
返回脚手架(
appBar:appBar(
标题:文本(“创建待办事项”),
),
正文:中(
子:ListView(
儿童:[
填充物(
填充:常数边集全部(8.0),
孩子:TextField(
一旦更改:(文本){
标题=文本;
},
装饰:输入装饰(hintText:“输入标题”),
),
),
填充物(
填充:常数边集全部(8.0),
孩子:TextField(
一旦更改:(文本){
正文=文本;
},
装饰:输入装饰(hintText:“输入正文”),
),
),
图标按钮(
图标:图标(Icons.send),
//如果包含数据,则发送else块
已按下:(){
如果(标题=“”| |正文=“”){
警报(上下文:context,标题:“Error”,描述:“请填写表单”,类型:AlertType.Error).show();
}否则{
_futureTodo=发送数据(标题、正文);
警报(上下文:上下文,标题:“成功”,描述:“存储成功”,类型:AlertType.Success,
按钮:[
对话框按钮(
子:文本(
“家”,
样式:TextStyle(颜色:Colors.white,字体大小:20),
),
已按下:(){
导航器。推(
上下文
MaterialPage路由(生成器:(上下文)=>MyApp()),
);
},
宽度:120,
),
对话框按钮(
子:文本(
“回来”,
样式:TextStyle(颜色:Colors.white,字体大小:20),
),
已按下:(){
导航器。推(
上下文
MaterialPage路由(生成器:(上下文)=>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 ');
    }
  }
}
类Api扩展了无状态小部件{
@凌驾
小部件构建(构建上下文){
返回脚手架(
浮动操作按钮:生成器(
生成器:(上下文){
返回浮动操作按钮(
已按下:(){
sendData(“默认”、“默认”)。然后((值){
Scaffold.of(context.showSnackBar(SnackBar(内容:Text(“欢迎”),)
});
},
);
},
),
);
}
Future sendData(字符串标题、字符串正文)异步{
final http.Response Response=wait http.post(
'http://192.168.1.20/Todo_api/public/todos/store',
标题:{
“内容类型”:“应用程序/json;字符集=UTF-8”,
},
正文:JSONECODE({
“标题”:标题,
“身体”:身体,
}),
);
如果(response.statusCode==200){
//200创建
//解析json
返回true;
}否则{
抛出异常('提交失败,请联系开发者');
}
}
}

这对我不起作用,主要是因为你不能在这个函数中返回bool,而且快餐店由于某种原因没有出现,但我会接受它作为答案,因为你给了我一个字符串来解决这个问题
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 ');
    }
  }
}