Flutter 知识点总结-进阶篇

Posted 王睿丶

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Flutter 知识点总结-进阶篇相关的知识,希望对你有一定的参考价值。

喜欢记得点个赞哟,我是王睿,很高兴认识大家!

1、http get请求数据、post提交数据、以及渲染动态数据

效果图:

导入: http: ^0.12.0+2库

Http_Back.dart

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

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

  _HttpDemoState createState() => _HttpDemoState();
}

class _HttpDemoState extends State<HttpDemo> {

  List _list=[];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    this._getData();
  }
  _getData() async{
    var apiUrl="http://a.itying.com/api/productlist";
    var result=await http.get(apiUrl);
    if(result.statusCode==200){
      print(result.body);
      setState(() {
       this._list=json.decode(result.body)["result"];

      /*
      {
        "result": [{
            "_id": "5ac0896ca880f20358495508",
            "title": "精选热菜",
            "pid": "0",		
          }, {
            "_id": "5ac089e4a880f20358495509",
            "title": "特色菜",
            "pid": "0",
            
          }
        ]
      }

      */

      });
    }else{
      print("失败${result.statusCode}");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("请求数据Demo"),
      ),
      body: this._list.length>0?ListView(
        children: this._list.map((value){
            return ListTile(
              title: Text(value["title"]),
            );
        }).toList(),
      ):Text("加载中...")
    );
  }
}

请求数据

  //请求数据
  _getData() async{

    var apiUrl="http://192.168.0.5:3000/news";

    var result=await http.get(apiUrl);
    if(result.statusCode==200){
      // print(json.decode(result.body));
      setState(() {
         this._news=json.decode(result.body)["msg"]; 
      });
    }else{
      print(result.statusCode);
    }
  }

提交数据

  _postData() async{
    var apiUrl="http://192.168.0.5:3000/dologin";

    var result=await http.post(apiUrl, body: {'username': '张三', 'age': '20'});
    if(result.statusCode==200){
      print(json.decode(result.body));      
    }else{
      print(result.statusCode);
    }
  }

2、Dio库实现网络请求以及动态渲染数据

导入第三方库:Dio库

请求数据

  _getData() async{
      var apiUrl="http://192.168.0.5:3000/news";    
      Response response = await Dio().get(apiUrl);
      print(response.data);
  }

提交数据

 _postData() async{
      Map jsonData={
        "username":"哈哈哈",
        "age":20
      };
      var apiUrl="http://192.168.0.5:3000/dologin";
      Response response = await Dio().post(apiUrl,data:jsonData);
      print(response.data);
  }

Dio Get请求数据、渲染数据

import 'dart:convert';

import 'package:flutter/material.dart';

import 'package:dio/dio.dart';

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

  _HttpDemoState createState() => _HttpDemoState();
}

class _HttpDemoState extends State<HttpDemo> {
  
  List _list=[];

  @override
  void initState() { 
    super.initState();
    this._getData();
  }

  _getData() async{
    var apiUrl="http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1";
    Response result=await Dio().get(apiUrl);

    // print(json.decode(result.data)["result"]);
    setState(() {
     this._list=json.decode(result.data)["result"]; 
    });  
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("请求数据Dio Demo"),
      ),
      body: this._list.length>0?ListView(
        children: this._list.map((value){
          return ListTile(
            title: Text(value["title"]),
          );
        }).toList(),
      ):Text("加载中...")
    );
  }
}

3、下拉刷新 上拉分页加载更多

效果图:


学习之前需要导入Dio库,具体用法与导入连接请查看我的博客
Flutter进阶第2篇:Dio库实现网络请求以及动态渲染数据

News.dart

import 'package:flutter/material.dart';

import 'dart:convert';
import 'package:dio/dio.dart';

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

  _NewsPageState createState() => _NewsPageState();
}

class _NewsPageState extends State<NewsPage> {
  List _list = [];
  int _page = 1;
  bool hasMore = true; //判断有没有数据
  ScrollController _scrollController = new ScrollController();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    this._getData();

    //监听滚动条事件
    _scrollController.addListener(() {
      print(_scrollController.position.pixels); //获取滚动条下拉的距离

      print(_scrollController.position.maxScrollExtent); //获取整个页面的高度

      if (_scrollController.position.pixels >
          _scrollController.position.maxScrollExtent - 40) {
        this._getData();
      }
    });
  }

  void _getData() async {
    if (this.hasMore) {
      var apiUrl =
          "http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=${_page}";

      var response = await Dio().get(apiUrl);
      var res = json.decode(response.data)["result"];   

      setState(() {
        this._list.addAll(res);  //拼接
        this._page++;
      });
      //判断是否是最后一页
      if (res.length < 20) {
        setState(() {
          this.hasMore = false;
        });
      }
    }
  }

  //下拉刷新
  Future<void> _onRefresh() async {
    await Future.delayed(Duration(milliseconds: 2000), () {
      print('请求数据完成');
      _getData();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("新闻列表"),
      ),
      body: this._list.length > 0
          ? RefreshIndicator(
              onRefresh: _onRefresh,
              child: ListView.builder(
                controller: _scrollController,
                itemCount: this._list.length, //20
                itemBuilder: (context, index) {//19                  
                  if (index == this._list.length-1) {   //列表渲染到最后一条的时候加一个圈圈
                    //拉到底
                     return Column(
                      children: <Widget>[
                        ListTile(
                          title: Text("${this._list[index]["title"]}",
                              maxLines: 1),
                        ),
                        Divider(),
                        _getMoreWidget()
                      ],
                    );

                  } else {
                    return Column(
                      children: <Widget>[
                        ListTile(
                          title: Text("${this._list[index]["title"]}",
                              maxLines: 1),
                        ),
                        Divider()
                      ],
                    );
                  }
                },
              ))
          : _getMoreWidget(),
    );
  }

  //加载中的圈圈
  Widget _getMoreWidget() {

    if(hasMore){
      return Center(
        child: Padding(
          padding: EdgeInsets.all(10.0),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              Text(
                '加载中...',
                style: TextStyle(fontSize: 16.0),
              ),
              CircularProgressIndicator(
                strokeWidth: 1.0,
              )
            ],
          ),
        ),
      );
    }else{
       return Center(
         child: Text("--我是有底线的--"),
       );
    }
  }
}

4、实现简单的新闻系统渲染新闻详情数据以及用flutter_html解析html

效果图:

点击这三个新闻列表的内容,即可进入新闻详情

学习之前需要导入Dio库,具体用法与导入连接请查看我的博客
Flutter进阶第2篇:Dio库实现网络请求以及动态渲染数据

还需要导入解析HTML代码的第三方库:
flutter_html

新闻列表代码:

import 'package:flutter/material.dart';

import 'dart:convert';
import 'package:dio/dio.dart';

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

  _NewsPageState createState() => _NewsPageState();
}

class _NewsPageState extends State<NewsPage> {
  List _list = [];
  int _page = 1;
  bool hasMore = true; //判断有没有数据
  ScrollController _scrollController = new ScrollController();

  @override
  void initState() {    
    super.initState();
    this._getData();

    //监听滚动条事件
    _scrollController.addListener(() {
      print(_scrollController.position.pixels); //获取滚动条下拉的距离

      print(_scrollController.position.maxScrollExtent); //获取整个页面的高度

      if (_scrollController.position.pixels >
          _scrollController.position.maxScrollExtent - 40) {
        this._getData();
      }
    });
  }

  void _getData() async {
    if (this.hasMore) {
      var apiUrl =
          "http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=${_page}";

      var response = await Dio().get(apiUrl);
      var res = json.decode(response.data)["result"];   
      setState(() {
        this._list.addAll(res);  //拼接
        this._page++;
      });
      //判断是否是最后一页
      if (res.length < 20) {
        setState(() {
          this.hasMore = false;
        });
      }
    }
  }

  //下拉刷新
  Future<void> _onRefresh() async {
    await Future.delayed(Duration(milliseconds: 2000), () {
      print('请求数据完成');
      _getData();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("新闻列表"),
      ),
      body: this._list.length > 0
          ? RefreshIndicator(
              onRefresh: _onRefresh,
              child: ListView.builder(
                controller: _scrollController,
                itemCount: this以上是关于Flutter 知识点总结-进阶篇的主要内容,如果未能解决你的问题,请参考以下文章

Kafka核心设计与实践原理总结:进阶篇

Flutter 知识点总结-基础篇

Flutter进阶篇(4)-- Flutter的Future异步详解

重走Flutter状态管理之路—Riverpod进阶篇

重走Flutter状态管理之路—Riverpod进阶篇

Vue基础知识总结:进阶篇