无法获取 itemCount 中的数据长度

Cant get data's length in itemCount

我想获取 API 数据的长度以在 Listview.builder 小部件中使用。我想从 API 获取我的数据,即 'mahalle'。而这个数据是一个数据列表。我想获取此数据的长度来构建列表。但是我得到了这样的错误:

#4      ComponentElement.performRebuild 
package:flutter/…/widgets/framework.dart:4546
...
════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by widgets library ═══════════════════════════════════
Class 'Future<dynamic>' has no instance getter 'length'.
Receiver: Instance of 'Future<dynamic>'
Tried calling: length
The relevant error-causing widget was
    MahalleList 

而错误的参考是:

@action
  Future<void> fetcMahalle() async {
    // var data =
    //     await httpClient.getData(globals.SELECT_URL).then((mahalle) => mahalle);
    networkService.getMahalle();
  }

我正在使用 :

获取数据
Future getMahalle() async {
    BaseOptions options = new BaseOptions(
      baseUrl: globals.PROD_URL,
      connectTimeout: 5000,
      receiveTimeout: 3000,
    );
    Dio dio = new Dio(options);
    dio.options.headers["Authorization"] = "Bearer ${globals.USER_TOKEN}";
    try {
      var response =
          await dio.get(globals.SELECT_URL); //'api/hizlirapor/selects'

      List<MahalleModel> mahalleList = response.data['mahalle']
          .map<MahalleModel>((mahalle) => MahalleModel.fromJson(mahalle))
          .toList();

      return mahalleList;
    } on DioError catch (e) {
      debugPrint("ERRORR!!!!!!!!!!!!! ${e.error.toString()}");
      return null;
    }
  }

最后是我尝试使用列表数据长度的小部件:

Container _buildBody(
      BuildContext context, ObservableFuture<List<MahalleModel>> future) {
    return Container(
      color: backgroundColor,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          _buildSearchBar(context),
          RefreshIndicator(
            onRefresh: mahalleStore.fetcMahalle,
            child: ListView.builder(
                physics: const AlwaysScrollableScrollPhysics(),
                itemCount: mahalleList.length,
                itemBuilder: (context, index) {
                  final mahalle = mahalleList[index];
                  return Container(
                    height: 100,
                    child: Card(
                      color: Colors.white,
                      margin: EdgeInsets.all(15),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.all(
                          Radius.circular(10),
                        ),
                      ),
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          Container(
                            color: mainColor,
                            width: 3,
                            height: 50,
                          ),
                          SizedBox(
                            width: 15,
                          ),
                          Icon(
                            AppIcon.mahalle_raporu,
                            color: mainColor,
                          ),
                          SizedBox(
                            width: 15,
                          ),
                          Text(
                            mahalle.mahalleAdi,
                            style: textStyle,
                          ),
                        ],
                      ),
                    ),
                  );
                }),
          ),
        ],
      ),
    );
  }

感谢大家的帮助!

你应该使用 FutureBuilder 因为 getMahalle returns 一个 Future.

FutureBuilder(
  future:mahalleStore.fetchMahalle,
  builder: (context, snapshot){
//whatever returns from this function, will be avaliable inside snapshot paremeter.
final mahalleList= snapshot.data;
switch (snapshot.connectionState) {
  case ConnectionState.waiting:
    {
      return Center(child: CircularProgressIndicator(),);
    }
  case ConnectionState.done:
    if (snapshot.hasData) {
      // do what you want here
    }
    return Text("Error occured");

  default:
    //
}});

我删除了之前的评论,检查一下这个。