Flutter使用本地mock数据模拟网络请求

路人甲
  • 24

问题描述

如何在本地使用mock数据来模拟类似的网络请求之后的页面加载

回复
阅读 3k
1 个回答
class BatchSub extends StatefulWidget {
  @override
  createState() => new BatchSubState();
}
class BatchSubState extends State<BatchSub> {
     var _selected = {};
     var _discount;
     var _futurePageData;
      void initState() {
        //  _initPageData();
        super.initState();
        _futurePageData = _initPageData();
      }
     Future _initPageData() async{
    return Future.delayed(new Duration(milliseconds: 200),(){
     var pageData = {
          "discountStatus": 1, //0:免费试用,1:限时打折,2:原价
          "subscribeStatus": "0", 
          "title": "限时免费", 
          "subTitle": "活动时间9月1日-9月30日", 
          "packageList": [
              {
                  "id": 23, 
                  "desc": "月度订阅", 
                  "dealPrice": 10, 
                  "originPrice": 50, 
                  "recommand": 1
              }, 
              {
                  "id": 33, 
                  "desc": "半年订阅", 
                  "dealPrice": 56, 
                  "originPrice": 280, 
                  "recommand": 0
              }, 
              {
                  "id": 56, 
                  "desc": "年度订阅", 
                  "dealPrice": 108, 
                  "originPrice": 540, 
                  "recommand": 0
              }
          ]
      };
      var packageLists = pageData['packageList'];
      setState(() {
        _discount = pageData['discountStatus'];
      });
      for (var item in packageLists) {
        if(item['recommand'] == 1){
          setState(() {
            _selected = item;
          });
        }
      }
      return pageData;
    });
    @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("优选访客订阅功能"),
      ),
      body: FutureBuilder(
        builder: _buildFuture,
        future: _futurePageData,
      ),
      // bottomNavigationBar:
      bottomNavigationBar: buildBottomBar(),
    );
  }
    //构建延迟加载的DOM
  Widget _buildFuture(BuildContext context, AsyncSnapshot snapshot) {
    switch (snapshot.connectionState) {
     case ConnectionState.none:
       print('还没有开始网络请求');
       return Text('还没有开始网络请求');
     case ConnectionState.active:
       print('active');
       return Text('ConnectionState.active');
     case ConnectionState.waiting:
      //  print('waiting');
       return Center(
         child: CircularProgressIndicator(),
       );
     case ConnectionState.done:
      //  print('done');
       if (snapshot.hasError) return Text('Error: ${snapshot.error}');
      //  print(snapshot.data);
      //  return Text('data');
       return buildBody(context, snapshot);
     default:
       return Text('还没有开始网络请求');
   }
}
你知道吗?

宣传栏