• flutter 网络加载和json解析(sunt aut facere repellat provident occaecati excepturi optio reprehenderit)


    sunt aut facere repellat provident occaecati excepturi optio reprehenderit 这是获取的json内容的title,仔细看清楚

    首先在pubspec.yaml中添加https://www.cnblogs.com/wf-l5201314/p/10315922.html

    导入完后

    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 response = await http.get('https://jsonplaceholder.typicode.com/posts/1', headers: {HttpHeaders.AUTHORIZATION: "Basic your_api_token_here"},);
      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();
                },
              ),
            ),
          ),
        );
      }
    }

    得到结果:sunt aut facere repellat provident occaecati excepturi optio reprehenderit(这是获取的json内容的title,仔细看清楚)表示网络获取参数成功

    然后再

    import 'dart:convert';
    
    import 'package:flutter/material.dart';
    import 'package:http/http.dart' as http;
    
    void main() {
      runApp(SampleApp());
    }
    
    class SampleApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Sample App',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: SampleAppPage(),
        );
      }
    }
    
    class SampleAppPage extends StatefulWidget {
      SampleAppPage({Key key}) : super(key: key);
    
      @override
      _SampleAppPageState createState() => _SampleAppPageState();
    }
    
    class _SampleAppPageState extends State<SampleAppPage> {
      List widgets = [];
    
      @override
      void initState() {
        super.initState();
    
        loadData();
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
            appBar: AppBar(
              title: Text("Sample App"),
            ),
            body: ListView.builder(
                itemCount: widgets.length,
                itemBuilder: (BuildContext context, int position) {
                  return getRow(position);
                }));
      }
    
      Widget getRow(int i) {
        return Padding(
            padding: EdgeInsets.all(10.0),
            child: Text("Row ${widgets[i]["title"]}")
        );
      }
    
      loadData() async {
        String dataURL = "https://jsonplaceholder.typicode.com/posts";
        http.Response response = await http.get(dataURL);
        setState(() {
          widgets = json.decode(response.body);
        });
      }
    }

    json的内容就出来了。你可以切换json数据源显示

    例如上面的换个数据源

    import 'dart:convert';
    
    import 'package:flutter/material.dart';
    import 'package:http/http.dart' as http;
    
    void main() {
      runApp(SampleApp());
    }
    
    class SampleApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Sample App',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: SampleAppPage(),
        );
      }
    }
    
    class SampleAppPage extends StatefulWidget {
      SampleAppPage({Key key}) : super(key: key);
    
      @override
      _SampleAppPageState createState() => _SampleAppPageState();
    }
    
    class _SampleAppPageState extends State<SampleAppPage> {
    
      var mapss =  Map();
      List widgets = [];
    
      @override
      void initState() {
        super.initState();
    
        loadData();
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
            appBar: AppBar(
              title: Text("Sample App"),
            ),
            body: ListView.builder(
                itemCount: widgets.length,
                itemBuilder: (BuildContext context, int position) {
                  return getRow(position);
                }));
      }
    
      Widget getRow(int i) {
        return Padding(
            padding: EdgeInsets.all(10.0),
            child: Text("第${i}行${widgets[i]["title"]}")
        );
      }
    
      loadData() async {
        String dataURL = "https://api.jisuapi.com/todayhistory/query?appkey=d52273a85bbe39fd%20&month=12&day=16";
        http.Response response = await http.get(dataURL);
        setState(() {
    //      widgets = json.decode(response.body);
    //      print("返回来啥:${json.decode(response.body)}");
          mapss = json.decode(response.body);
          widgets = mapss["result"];
          print("返回来啥:${widgets}");
        });
      }
    }
  • 相关阅读:
    剑指offer39-平衡二叉树
    剑指offer37-数字在排序数组中出现的次数
    剑指offer36-两个链表的第一个公共结点
    剑指offer31-整数中1出现的次数
    剑指offer30-连续子数组的最大和
    剑指offer28-数组中出现次数超过一半的数字
    剑指offer26-二叉搜索树与双向链表
    剑指offer21-栈的压入、弹出序列
    剑指offer16-合并两个排序的链表
    C#-杂碎
  • 原文地址:https://www.cnblogs.com/gaozhang12345/p/12049850.html
Copyright © 2020-2023  润新知