Flutter url获取数据

import 'dart:async';
import 'dart:convert';

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

//发起网络请求
Future fetchPost() async{
  final response = await http.get('https://jsonplaceholder.typicode.com/posts/1');
  final responseJson = json.decode(response.body);
  return Post.fromJson(responseJson);
}
//将返回的内容转换为Dart 对象
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 json){
    return Post(
      userId: json['userId'],
      id: json['id'],
      title: json['title'],
      body: json['body'],
    );
  }
}

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var appBar2 = AppBar(
          title: Text('Demo2'),
        );
    return MaterialApp(
      title: 'Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: appBar2,
        body: Center(
          //获取显示数据
          child: FutureBuilder(
            future: fetchPost(),
            builder: (context,snapshot) {
              if(snapshot.hasData){
                return Text(snapshot.data.title);
              } else if (snapshot.hasError) {
                return Text('${snapshot.error}');
              }
              return CircularProgressIndicator();
            },
          ),
        ),
      ),
    );
  }
}

参考:https://flutterchina.club/cookbook/

你可能感兴趣的:(#,Flutter,实例)