import 'dart:convert';

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

class HttpDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("http_demo"),
      ),
      body: HttpDemoHome(),
    );
  }
}

class HttpDemoHome extends StatefulWidget {
  @override
  _HttpDemoHomeState createState() => _HttpDemoHomeState();
}

class _HttpDemoHomeState extends State<HttpDemoHome> {
  @override
  void initState() {
    super.initState();
    //requst network
    // fetchPost();
    final post = {"title": "Hello", "description": "nice to meet you."};
    print(post['title']);
    print(post['description']);
    //map to json
    final postJson = json.encode(post);
    print(postJson);
    //json to map
    final postJsonConverted = json.decode(postJson);
    print(postJsonConverted['title']);
    print(postJsonConverted is Map);
    //map to model
    final postModel = Post.fromJson(postJsonConverted);
    print("title:${postModel.title}");
    print("description:${postModel.description}");
    //model print
    print("description:${postModel.tojson()}");
  }

  @override
  Widget build(BuildContext context) {
    return Container();
  }

  void fetchPost() async {
    var url = Uri.parse('https://resources.ninghao.net/demo/posts.json');
    final response = await http.get(url);
    print(response.statusCode);
    print(response.body);
  }
}

class Post {
  final String title;
  final String description;

  Post(this.title, this.description);

  Post.fromJson(Map json)
      : title = json['title'],
        description = json['description'];

  Map tojson() => {'title': title, 'description': description};
}

输出

I/flutter (27104): Hello
I/flutter (27104): nice to meet you.
I/flutter (27104): {"title":"Hello","description":"nice to meet you."}
I/flutter (27104): Hello
I/flutter (27104): true
I/flutter (27104): title:Hello
I/flutter (27104): description:nice to meet you.
I/flutter (27104): description:{title: Hello, description: nice to meet you.}
 

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐