如何在Flutter中发布数据?

时间:2019-11-12 09:21:11

标签: flutter

任何人都知道发布数据的正确方法。我有一个例外:提取数据时出错...任何有张贴数据示例的人

示例代码:

   import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class Post {
  final String userId;
  //final int id;
  final String title;
 // final String body;

  Post({this.userId, this.title, });

  factory Post.fromJson(Map<String, dynamic> json) {
    return Post(
      userId: json['id'],
     // id: json['id'],
      title: json['name'],
     // body: json['body'],
    );
  }

  Map toMap() {
    var map = new Map<String, dynamic>();
    map["id"] = userId;
    map["name"] = title;

    return map;
  }
}

Future<Post> createPost(String url, {Map body}) async {
  return http.post(url, body: body).then((http.Response response) {
    final int statusCode = response.statusCode;

    if (statusCode < 200 || statusCode > 400 || json == null) {

      print(statusCode);
      throw new Exception("Error while fetching data");

    }
    return Post.fromJson(json.decode(response.body));
  });
}

class Postdata extends StatelessWidget {
  final Future<Post> post;

  Postdata({Key key, this.post}) : super(key: key);
  static final CREATE_POST_URL = 'http://192.168.1.224:8520/dummy/postDummy/';
  TextEditingController titleControler = new TextEditingController();
  TextEditingController bodyControler = new TextEditingController();

  @override
  Widget build(BuildContext context) {
// TODO: implement build
    return MaterialApp(
      title: "WEB SERVICE",
      theme: ThemeData(
        primaryColor: Colors.deepOrange,
      ),
      home: Scaffold(
          appBar: AppBar(
            title: Text('Create Post'),
          ),
          body: new Container(
            margin: const EdgeInsets.only(left: 8.0, right: 8.0),
            child: new Column(
              children: <Widget>[
                new TextField(
                  controller: titleControler,
                  decoration: InputDecoration(
                      hintText: "title....", labelText: 'Post Title'),
                ),
                new TextField(
                  controller: bodyControler,
                  decoration: InputDecoration(
                      hintText: "body....", labelText: 'Post Body'),
                ),
                new RaisedButton(
                  onPressed: () async {
                    Post newPost = new Post(
                        userId: "120",  title: titleControler.text,/* body: bodyControler.text*/);
                    Post p = await createPost(CREATE_POST_URL,
                        body: newPost.toMap());
                    print(p.title);
                    print(newPost);
                  },
                  child: const Text("Create"),
                )
              ],
            ),
          )),
    );
  }
}

0 个答案:

没有答案