gpt4 book ai didi

dart - 如何修复 FutureBuilder 打开多次错误?

转载 作者:行者123 更新时间:2023-12-03 03:07:38 25 4
gpt4 key购买 nike

这是我的两个类(两页)。这两个类(class)多次开放。
我将调试点放在 futurebuilder 中的两个类中。
调试点运行,

  • MainCategory 页面并进入下一页
  • SubCategory 页面并再次运行 MainCategory 页面(上一页)futurebuilder 并再次运行 MainCategory 页面 futurebuilder
  • 将子类别页面导航到运行子类别页面和主类别页面的第三页

  • 我将我的两个类上传到 GitHub,请告诉我问题是什么。

    主要分类代码: https://github.com/bhanuka96/ios_login/blob/master/MainCategory.dart
    子类别代码: https://github.com/bhanuka96/ios_login/blob/master/subCategory.dart

    最佳答案

    如文档中所述,您不应在小部件的构建事件期间为 Futurebuilder 获取 Future。

    https://docs.flutter.io/flutter/widgets/FutureBuilder-class.html

    The future must have been obtained earlier, e.g. during State.initState, State.didUpdateConfig, or State.didChangeDependencies. It must not be created during the State.build or StatelessWidget.build method call when constructing the FutureBuilder. If the future is created at the same time as the FutureBuilder, then every time the FutureBuilder's parent is rebuilt, the asynchronous task will be restarted.



    所以,试着把你的电话转到 getRegister build 方法之外的方法并将其替换为返回的 Future 值。

    例如,下面我有一个返回 Future 值的类,它将在 FutureBuilder 的帮助下使用。
    class MyApiHelper{

    static Future<List<String>> getMyList() async {
    // your implementation to make server calls
    return List<String>();
    }
    }

    现在,在您的小部件中,您将拥有如下内容:
    class _MyHomePageState extends State<MyHomePage> {

    Future<List<String>> _myList;

    @override
    void initState() {
    super.initState();

    _myList = MyApiHelper.getMyList();
    }

    @override
    Widget build(BuildContext context) {
    return Scaffold(body: FutureBuilder(
    future: _myList,
    builder: (_, AsyncSnapshot<List<String>> snapLs) {
    if(!snapLs.hasData) return CircularProgressIndicator();

    return ListView.builder(
    itemCount: snapLs.data.length,
    itemBuilder: (_, index) {
    //show your list item row here...
    },
    );
    },
    ));
    }
    }

    如上所示,Future 是在 initState 中获取的函数和内部使用 build方法和使用 FutureBuilder .

    我希望这可以帮到你。
    谢谢。

    关于dart - 如何修复 FutureBuilder 打开多次错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55738094/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com