Flutter 获取服务器数据

文档 文档版本有些老
使用 dio 来获取数据

demo

import 'dart:io';
import 'dart:convert';

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Ajnauw',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  var users = [];

  List<Widget> _generatorItem() {
    return users.map((u) {
      String name = u['name'];
      return ListTile(
        leading: CircleAvatar(
          backgroundColor: Colors.grey.shade800,
          child: Text('$name'[0]),
        ),
        title: Text(name),
      );
    }).toList();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('demo'),
      ),
      body: ListView(
        children: <Widget>[
          Container(
            child: Column(
              children: <Widget>[
                RaisedButton(
                  color: Theme.of(context).primaryColor,
                  onPressed: () async {
                    try {
                      // 使用端口而不是 localhost  https://github.com/hillelcoren/flutter-redux-starter/issues/16
                      var url = Uri.parse('http://192.168.150.115:5000/test');
                      var httpClient = new HttpClient();

                      var request = await httpClient.getUrl(url);
                      var response = await request.close();

                      var data =
                          await response.transform(utf8.decoder).toList();
                      String body = data.join('');
                      // print(body);
                      setState(() {
                        users = jsonDecode(body);
                      });
                      httpClient.close();
                    } catch (e) {
                      print(e);
                    }
                  },
                  child: Text('Get List'),
                ),
              ],
            ),
          ),
          Offstage(
            offstage: users.isEmpty,
            child: Container(
              child: Column(
                children: _generatorItem(),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

接口代码

  @Get('test')
  getHello(): Array<User> {
    return [new User('ajanuw'), new User('suou')];
  }
上一篇:KindEditor:Ajax提交表单时获取不到HTML内容


下一篇:微信小程序-高德地图API获取天气信息