Flutter之FutureBuilder组件的使用

import 'dart:convert';
import "package:http/http.dart" as http;

import 'package:flutter/material.dart';

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

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  Future<List> requestGet() async {
    final response = await http.get('https://kyfw.12306.cn/otn/queryDishonest/query');
    Utf8Decoder utf8decoder = Utf8Decoder();
    var result = await json.decode(utf8decoder.convert(response.bodyBytes));
    return result['data']['right'];
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        debugShowCheckedModeBanner:false,
      home: Scaffold(
        appBar: AppBar(
          title: Text('12306失信名单'),
        ),
        body: FutureBuilder<List>(
          future: requestGet(),
          // ignore: missing_return
          builder: (BuildContext context, AsyncSnapshot<List> snapshot) {
            switch (snapshot.connectionState) {
              case ConnectionState.none:
                return new Text('Input a URL to start');
              case ConnectionState.waiting:
                return new Center(child: new CircularProgressIndicator());
              case ConnectionState.active:
                return new Text('');
              case ConnectionState.done:
                if (snapshot.hasError) {
                  return new Text(
                    '${snapshot.error}',
                    style: TextStyle(color: Colors.red),
                  );
                } else
                  return ListView(
                   children: getData(snapshot.data),
                  );
            }
          },
        ),
      ),
    );
  }
}

List<Widget> getData(List list){
  var listData = list.map((value){
    return ListTile(
      title: Text(value['passenger_id_no']),
      trailing: Text(value['passenger_name']),
      leading: Text(value['start_date']),
    );
  });
  return listData.toList();
 }
发布了66 篇原创文章 · 获赞 36 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/u013600907/article/details/100269239