api - 无法在itemCount中获取数据长度

标签 api flutter asynchronous dart future

我想获取要在Listview.builder小部件中使用的API数据的长度。我想从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(
  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:
    //
}});
我删除了之前的评论,请选中此评论。

关于api - 无法在itemCount中获取数据长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63722565/

相关文章:

api - 我应该为外部服务设置哪个超时?

php - laravel 5.6 在资源响应中保留数组自定义键

flutter - 找不到 flutter 命令/flutter 医生

flutter - 如何在 Flutter 中移动 Scaffold 的 body 和 bottomSheet?

javascript - 如何处理 JavaScript 中的 setTimeout 错误?

ruby-on-rails - 带响应的异步 Rails 操作

python - 星球大战 api => IndexError : list index out of range error

api - 在 Trello API 中调用通知/全部/读取时请求未经授权的通知

flutter - Flutter for Web 生成的标签,<flt-*> 是什么?

javascript - 在 map 函数之后执行函数