【问题标题】:Flutter App builder calling itself multiple timesFlutter App builder 多次调用自身
【发布时间】:2020-12-23 17:13:53
【问题描述】:

我是 Flutter 的新手,正在尝试使用 woocommerce api 构建电子商务移动应用。但是我面临着颤振未来构建者多次调用自己的挑战,我已经通过这个Post 实施了建议,但我得到了错误type 'Future' is not a subtype of type 'Future这是 API 类

Class APIService {

  final AsyncMemoizer _memoizer = AsyncMemoizer(); 

  Future<List<Category>> getCategories() {
    List<Category> data = new List<Category>();

    return this._memoizer.runOnce(() async {
       try {
      String url = Config.url +
          Config.categoriesURL +
          "?include=${Config.parentCAT}&consumer_key=${Config.key}&consumer_secret=${Config.secret}";
      var response = await Dio().get(url,
          options: new Options(headers: {
            HttpHeaders.contentTypeHeader: "application/json",
          }));

      if (response.statusCode == 200) {
        data =
            (response.data as List).map((i) => Category.fromJson(i)).toList();
      }
    } on DioError catch (e) {
      print(e.response);
    }
    return data;
     
    });  
  }

And this is the futurebuilder Stateful Class

class ParentCategories extends StatefulWidget {
  ParentCategories({Key key}) : super(key: key);

  @override
  _ParentCategoriesState createState() => _ParentCategoriesState();
}

class _ParentCategoriesState extends State<ParentCategories> {
  APIService apiService;

  @override
  void initState() {
    apiService = new APIService();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(
        top: 10,
      ),
      child: Container(
        color: Colors.white,
        child: Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Padding(
                  padding: EdgeInsets.only(left: 16, top: 10),
                  child: Text(
                    "Categories",
                    style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                  ),
                ),
                Padding(
                  padding: EdgeInsets.only(right: 16, top: 10),
                  child: Text(
                    "View All",
                    style: TextStyle(fontSize: 14, color: secondaryColor),
                  ),
                ),
              ],
            ),
            _categoriesList()
          ],
        ),
      ),
    );
  }

  Widget _categoriesList() {
    return new FutureBuilder(
        future: apiService.getCategories(),
        builder: (
          BuildContext context,
          model,
        ) {
          if (model.hasData) {
            return _buildCategoryList(model.data);
          }
          return Center(
            child: CircularProgressIndicator(),
          );
        });
  }

  Widget _buildCategoryList(List<Category> categories) {
    return Container(
      height: 100,
      alignment: Alignment.center,
      child: ListView.builder(
        shrinkWrap: true,
        physics: ClampingScrollPhysics(),
        scrollDirection: Axis.horizontal,
        itemCount: categories.length,
        itemBuilder: (context, index) {
          var data = categories[index];
          return Column(
            children: [
              Container(
                margin: EdgeInsets.all(10),
                width: 50,
                height: 50,
                alignment: Alignment.center,
                child: Image.network(
                  data.image.url,
                  height: 50,
                ),
                // decoration: BoxDecoration(
                //     shape: BoxShape.circle,
                //     color: Colors.white,
                //     boxShadow: [
                //       BoxShadow(
                //           color: Colors.black12,
                //           offset: Offset(0, 5),
                //           blurRadius: 15),
                //     ]),
              ),
              Padding(
                padding: const EdgeInsets.fromLTRB(8, 1, 5, 1),
                child: Row(
                  children: [
                    Text(
                      data.categoryName.toString(),
                      style: TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    // Icon(
                    //   Icons.keyboard_arrow_right,
                    //   size: 14,
                    // ),
                  ],
                ),
              ),
            ],
          );
        },
      ),
    );
  }
}```

【问题讨论】:

  • 这里的错误类型“Future”不是“Future 类型的子类型,您将 Future 作为子类型传递,您需要传递相同类型的 List 或 yiu 传递的任何内容

标签: flutter flutter-layout


【解决方案1】:

错误与 getCategories() 函数有关。在这里您期望返回 Future> 但您返回的是未来。 这部分代码

return this._memoizer.runOnce(() async {}

正在返回我猜想返回列表的未来。

标有async的函数总是返回一个Future

this._memoizer.runOnce()getCategories() 函数 asyncawait 设置为返回列表。
试试这个。

【讨论】:

  • 代码现在可以正常工作,没有 ErrorsFuture&lt;List&lt;Category&gt;&gt; getCategories() 更改为 Future&lt;dynamic&gt; getCategories() 但 Future builder 继续触发。
  • 我似乎没有找到确切的问题,但我认为问题可能与 getCategories() 函数有关。尝试首先保存您从该 api 调用返回的值,然后而是返回该变量。
猜你喜欢
  • 2021-03-22
  • 2019-08-30
  • 1970-01-01
  • 2021-03-05
  • 1970-01-01
  • 2021-02-17
  • 2021-08-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多