Flutter FutureBuilder異步請求列表示例

Flutter的FutureBuilder列表示例less

import 'package:flutter/material.dart';
import '../service/service_method.dart';

class CartPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var formData = {'adCode': '000000', 'isDebug':'aa'};
    return Scaffold(
      body: FutureBuilder( //異步請求再渲染 不用setState改變狀態
        future: request('get','chinaAddr',formData:formData), //可選參數formData:formData=屬性名:屬性值
        builder: (context, snapshot){ //snapshot就是_calculation在時間軸上執行過程的狀態快照
           if(snapshot.hasData){ //判斷有沒有值
              //print(snapshot.data);

              //數據處理
              var data = snapshot.data;
              List<Map> chinaData = (data['data'] as List).cast();
              //print(chinaData);

              return ListView.builder(
                itemCount: chinaData.length,
                itemBuilder: (context, index) {
                  final Map<String, dynamic> item = (chinaData)[index];
                  return ListTile(
                    title:  Text('${item["adName"]}'),
                    subtitle: Text('${item["adCode"]}'),
                  );
                }
              );

           }else{
              return Center(
                child: Text('加載中...'),
              );
           }
         }  
      ),
    );
  }
}

效果圖:異步

 

相關文章
相關標籤/搜索