码迷,mamicode.com
首页 > Web开发 > 详细

flutter http get请求

时间:2020-01-07 00:43:19      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:json   enter   post   return   state   def   code   syn   indicator   

 

import dart:async;
import dart:convert;

import package:flutter/material.dart;
import package:http/http.dart as http;

Future<Post> fetchPost() async {
  final response =
  await http.get(https://jsonplaceholder.typicode.com/posts/1);
  final responseJson = json.decode(response.body);

  return new Post.fromJson(responseJson);
}

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

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

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

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: Fetch Data Example,
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new Scaffold(
        appBar: new AppBar(
          title: new Text(Fetch Data Example),
        ),
        body: new Center(
          child: new FutureBuilder<Post>(
            future: fetchPost(),
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return new Text(snapshot.data.title);
              } else if (snapshot.hasError) {
                return new Text("${snapshot.error}");
              }

              // By default, show a loading spinner
              return new CircularProgressIndicator();
            },
          ),
        ),
      ),
    );
  }
}

 

 

 

 

 

flutter http get请求

标签:json   enter   post   return   state   def   code   syn   indicator   

原文地址:https://www.cnblogs.com/sea-stream/p/12158967.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!