ListView of flutter learning diary, network request to dynamically update listview

 

Listview is usually used in Android. So how to use it in flutter.

You can see the introduction to listview in the flutter official website document:

In Android ListView, you can create an adapter, and then you can pass it to ListView, which will use the content returned by the adapter to display each row. However, you must make sure to recycle the rows at the right time, otherwise, you will get all kinds of crazy visual and memory problems.

In Flutter, due to Flutter's immutable widget model, a list of Widgets is passed to the ListView, and Flutter will be responsible for ensuring that they scroll quickly and smoothly.

You can directly new listview():

 @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("Sample App"),
      ),
      body: new ListView(children: _getListData()),
    );
  }

  _getListData() {
    List<Widget> widgets = [];
    for (int i = 0; i < 100; i++) {
      widgets.add(new Padding(padding: new EdgeInsets.all(10.0), child: new Text("Hello, world.")));
    }
    return widgets;
  }

Or through listview.Builder(): When you have a large list of data, it will automatically recycle the list elements for you.

 body: ListView.builder(
            itemCount: list == null ? 0 : list.length,
            itemBuilder: (BuildContext context, int position) {
              return _getListDate(context, position);
            }),
      ),
itemCount表示长度相当于AndroidAdapter的getCount().
itemBuilder()里面返回当前position下的视图.
_getListDate返回视图.相当于Android adapter的getview().
  Widget _getListDate(BuildContext context, int position) {
    if (list != null) {
        return GestureDetector(
          onTap: () {
            showMessage(list[position]);
          },
          child: Center(
              child: new Container(
                  width: getScreenWidth(context),
                  decoration: BoxDecoration(
                    color: Colors.white,
                  ),
                  margin: EdgeInsets.only(top: 2.0),
                  padding: EdgeInsets.only(top: 10.0, bottom: 10.0),
                  child: Center(child: new Text(list[position])))),
        );
    }
  }

If we get the data from the interface at the beginning our itemCount is definitely 0, then we have to request the interface to get the data to refresh the UI.

I use flutter's HttpClient() for network requests; here you need to import the package import'dart:io';

 _getdata() async {
    if (list != null) {
      return;
    }
   // 创建一个HTTP client
    var httpClient = new HttpClient();
    //创建一个url Uri.http();这里指定的是http请求,也可以https.可以看见第一个参数给的时候没有加上http://,加了会报错.第三个参数带上了请求Parameter.
    var url = new Uri.http('api.xxx.xxx', '/config/profession',
        {'accessToken': 'xxxxxxxxxxxx'});
    var requset = await httpClient.getUrl(url);
    var close = await requset.close();
    var boby = await close.transform(UTF8.decoder).join();
    //JSON解析拿到数据.
    Map mapJson = JSON.decode(boby);
    //拿到listview列表的数据.
    list = mapJson['data'];
    print(JSON.decode(boby));
    //更新视图.
    setState(() {});
  }

At this point, a simple dynamic update of the listview through a network request is basically achieved.

Guess you like

Origin blog.csdn.net/qq_36767261/article/details/82015203