1

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

#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,
                          ),
                        ],
                      ),
                    ),
                  );
                }),
          ),
        ],
      ),
    );
  }

感谢您的所有帮助!

4

2 回答 2

2
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:
    //
}});

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

于 2020-09-03T11:49:51.727 回答
1

您应该使用FutureBuilder,因为getMahalle返回一个Future.

于 2020-09-03T11:33:24.983 回答