【问题标题】:How to use Listview builder to display api response data如何使用 Listview builder 显示 api 响应数据
【发布时间】:2021-10-16 18:15:05
【问题描述】:

我想创建一个像这样的记录列表

可以是多个,取决于 api 响应数据的长度。所以为此我尝试使用futurebuilder 并在其中使用ListView.builder 创建这个输出设计,但它给了我这个错误。

错误:

═══════ Exception caught by widgets library ═══════════════════════════════════
The getter 'length' was called on null.
Receiver: null
Tried calling: length
The relevant error-causing widget was
FutureBuilder<List<leaveHistory>>

════════════════════════════════════════════════════════════════════════════════
I/flutter (18266): DioError [DioErrorType.response]: Http status error [300]


代码:


class leaveHistory{
  
  final String date;
  final String fromdate;
  final String todate;
  final String description;
  final String type;
  final String Status;
  leaveHistory(this.date, this.fromdate, this.todate,this.description,this.type,this.Status);

}
class _LeaveHistoryState extends State<LeaveHistory> {

List<leaveHistory> historyList=[];

 Future<List<leaveHistory>> _getRecord() async{
   Dio dio=new Dio();
   var data={
     'username':getname,
     'token':getaccesstoken,
   };
   return dio
    .post(localhostUrlLeaveHistoryON,data: json.encode(data))
      .then((onResponse) async {

        Map<String, dynamic> map=onResponse.data;
        List<dynamic> data = map["data"];
        for (var h in data) {
          leaveHistory history = leaveHistory(
            h["Date"], 
            h["description"], 
            h["type"],
            h['fromdate'],
            h["todate"],
            h["leave"]
          );
          historyList.add(history);
          print(historyList);   //its output is Instance of 'leaveHistory'

        }
        return historyList;
      })
      .catchError((onerror){
        print(onerror.toString());
       
    });
  }


 Widget build(BuildContext context) {
     body:Stack(children: <Widget>[
       

    Container(
    padding: EdgeInsets.fromLTRB(15, 150, 0, 0),
    child:SingleChildScrollView(
      scrollDirection: Axis.vertical,
    
    child: FutureBuilder(
      
    
    future: _getRecord(),  //error points here
    
    builder: (BuildContext context, AsyncSnapshot<List<leaveHistory>> snapshot) {
      if(snapshot.data.length==null){
      return Center(
        heightFactor: 10,
        child:Text("Data is not avaliable",style: TextStyle(color: Colors.blue[900],fontWeight: FontWeight.bold,fontSize: 20),));
      }
      else{
        return ListView.builder(
          scrollDirection: Axis.vertical,
          shrinkWrap: true,
          itemCount: snapshot.data.length,
          itemBuilder: (BuildContext context,int index){
        return ListTile(
            title: Text(snapshot.data[index].Status),
        );
      },);
      }
    }
  ),
),)

   

    ]));
  }
}


请帮我解决它。

【问题讨论】:

  • 试试我的回答here希望对你有帮助

标签: flutter listview flutter-futurebuilder


【解决方案1】:

将 Listview.builder 包装在展开的小部件中

Expanded(
   child: ListView.builder(itemCount: snapshot.data.length,
      shrinkWrap: true,
      itemBuilder: (BuildContext context,int index){
        return ListTile(
            title: Text(snapshot.data[index].Status),
        );
      },)
)

【讨论】:

  • 是的,我用它解决了我的问题,但我遇到的一个问题是当我重定向到屏幕时它显示此错误The getter 'length' was called on null. Receiver: null Tried calling: length 这是 dio 300 错误,然后几秒钟后它显示记录
  • 你能帮我解决这个问题吗
  • 您正在检查 snapshot.data.length==nullsnapshot.data 最初为空。将其替换为if(!snapshot.hasData || snapshot.data.length==0)
猜你喜欢
  • 2020-12-10
  • 2020-10-29
  • 1970-01-01
  • 1970-01-01
  • 2022-08-18
  • 1970-01-01
  • 1970-01-01
  • 2021-11-24
  • 1970-01-01
相关资源
最近更新 更多