http_post.dart 1.61 KB
Newer Older
1 2 3 4
// Copyright 2015, the Flutter project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

5 6
import 'dart:async';

7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
import 'package:flutter/http.dart' as http;
import 'package:flutter/material.dart';

void main() {
  runApp(
    new MaterialApp(
      title: "HTTP POST Example",
      routes: {
        '/': (RouteArguments args) => const PostDemo()
      }
    )
  );
}

class PostDemo extends StatefulComponent {
  const PostDemo();
  PostDemoState createState() => new PostDemoState();
}

class PostDemoState extends State<PostDemo> {

  String _response = null;

  void initState() {
    _refresh();
    super.initState();
  }

35
  Future _refresh() async {
36 37 38
    setState(() {
      _response = null;
    });
39 40
    http.Response response = await http.post(
      "http://httpbin.org/post",
41 42
      body: '{"foo": "bar"}',
      headers: { "Content-Type": "application/json", "baz": "qux" }
43 44 45
    );
    setState(() {
      _response = response.body;
46 47 48 49 50 51 52 53 54 55
    });
  }

  Widget build(BuildContext context)  {
    return new Scaffold(
      toolBar: new ToolBar(
        center: new Text("HTTP POST example")
      ),
      body: new Material(
        child: new Block(
56 57 58 59 60 61
          children: <Widget>[
            new Text(
              "${_response ?? 'Loading...'}",
              style: Typography.black.body1
            )
          ]
62 63 64 65 66 67 68 69 70 71 72
        )
      ),
      floatingActionButton: new FloatingActionButton(
        child: new Icon(
          icon: 'navigation/refresh'
        ),
        onPressed: _refresh
      )
    );
  }
}