getter 'length' 被调用为 null。接收者:空尝试调用:长度 I

时间:2021-07-12 12:30:48

标签: flutter dart

这段代码在这一行抛出异常

if (snapshot.hasData && snapshot.data.length > 1) {

错误是:

The getter 'length' was called on null.
Receiver: null
Tried calling: length
 @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Detail Of " + widget.barcode),
      ),
      body: FutureBuilder<dynamic>(
        future: fetchAlbum(),
        builder: (context, snapshot) {
          if (snapshot.hasData && snapshot.data.length > 1) {
            return ListView(
              padding: const EdgeInsets.all(8),
              children: snapshot.data.map<Widget>((e) {
                return Column(
                  children: [
                    ListTileLocal(e['title'], e['value'].toString()),
                    Divider(color: Colors.black)
                  ],
                );
              }).toList(),
            );
          } else if (snapshot.hasError) {
            return Center(
              child: Text(
                "No Barcode Found",
                style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
              ),
            );
          } else if (snapshot.data.length == 0) {
            return Center(
              child: Text("Invalied Barcode"),
            );
          }

          // By default, show a loading spinner.
          return Container(
              child: Center(
            child: CircularProgressIndicator(),
          ));
        },
      ),
    );
  }
}

3 个答案:

答案 0 :(得分:0)

您正在调用空数据的长度。使用 apk add build-base 运算符,您不会在尝试调用 && 之前检查数据是否为空。 使用 snapshot.data.length 应该可以防止调用 if

null

答案 1 :(得分:0)

仅当快照有数据时才调用 snapshot.data.length > 1。

FutureBuilder(
  future: myFuture,
  builder: (context, AsyncSnapshot snapshot) {
    // Try adding this print to your code to see when this method is being executed!
    print('Building with snapshot = $snapshot');

    if (snapshot.hasData) {
      // return widget with data - in your case, check the length and return the listview here.
    }
    else if (snapshot.hasError) {
      // return widget informing of error
    }
    else {
      // still loading, return loading widget (for example, a CircularProgressIndicator)
    }
  },
);

答案 2 :(得分:0)

快照可能有也可能没有一些数据,在调用一些内置函数之前,比如长度,检查它是否不为空很重要

你做到了

if (snapshot.hasData && snapshot.data.length > 1) 

//if the snapshot does not have data, it means snapshot.data=null; and as
//you are using && (and) operator it will check length on null and will
//throw error

正确的方法是

if(snapshot.hasData) {

//hence here snapshot has some data and you can use .lenght on it 
 if(snapshot.data.length > 1) {
  }
}else{

}