【问题标题】:How to use InitState when using Future Function and Future builder in flutter在flutter中使用Future Function和Future builder时如何使用InitState
【发布时间】:2021-07-07 19:36:35
【问题描述】:

我在 Flutter 中遇到问题。我不习惯有效地使用未来函数。 我试图从有状态类的 InitSate 中的 Future 函数中获取一个值,然后使用 Future Builder 中的返回值。 但是,当我在 initstate 中执行 l_orders = await xyz();l_orders = xyz(); 时,它不起作用我的屏幕无法加载它总是只显示 CircularProgressIndicator。

但是,当我将 l_orders = xyz(); 移到 InitState 之外时,一切正常。我想在 InitState 中执行此操作,因为稍后我也想使用 setState。所以这是我在进入 setState 部分之前的第一步。

我们非常感谢任何形式的帮助。谢谢你

我的代码是 -

class _OrderScreenState extends State<OrderScreen> {

  Future<String> xyz() async{
    return("processing ....");
  }

  @override
  Widget build (BuildContext context) {
    final orders = Provider.of<Orders>(context);
    var l_orders;

    @override
    void initState() async {
      super.initState();
      l_orders = await xyz();
    }


    return WillPopScope(
      onWillPop: () async {
        return false;
      },
      child: Scaffold(
        appBar: AppBar(
          title: Text('Orders'),
          actions: <Widget>[Padding(
            padding: const EdgeInsets.all(8.0),
            //child: IconButton(icon:Icon(Icons.home, size: 30,),onPressed: (){Navigator.of(context).pushNamed(HomePage.routeName);},),
          ),],
        ),
        body: FutureBuilder(
          future: l_orders,
          builder: (BuildContext context, AsyncSnapshot snapshot) {
            if (!snapshot.hasData) {
              // while data is loading:
              return Center(
                child: CircularProgressIndicator(backgroundColor: Colors.red,valueColor: new AlwaysStoppedAnimation<Color>(Colors.blue)),
              );
            } else {
              // data loaded:
             return Text("Test");
            }
          },
        ),

        floatingActionButton: FloatingActionButton(

          onPressed: (){Navigator.of(context).pushNamed(HomePage.routeName);},
          child: Icon(Icons.home,size: 40,),
          //backgroundColor: Colors.green,
        ),
        floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
       ),
    );
  }
} 

【问题讨论】:

    标签: flutter flutter-futurebuilder


    【解决方案1】:

    您没有将Future 传递给FutureBuilderl_orders 实际上是 String,因为您在 initState 中使用 awaiting 它。 不要在initState 中使用await,即使静态分析可能允许您这样做。

    initState 应该如下:

    @override
    void initState() {
      super.initState();
      l_orders = xyz();
    }
    

    此外,您的所有成员和您的initState 声明都在build 中。将它们移到 build 之外的类的正文中。

    class _OrderScreenState extends State<OrderScreen> {
      var l_orders;
    
      @override
      void initState() {
        super.initState();
        l_orders = xyz();
      }
    
      Future<String> xyz() async{
        return("processing ....");
      }
    
      @override
      Widget build (BuildContext context) {
        return WillPopScope(
          onWillPop: () async {
            return false;
          },
          child: Scaffold(
            appBar: AppBar(
              title: Text('Orders'),
              actions: <Widget>[Padding(
                padding: const EdgeInsets.all(8.0),
                //child: IconButton(icon:Icon(Icons.home, size: 30,),onPressed: (){Navigator.of(context).pushNamed(HomePage.routeName);},),
              ),],
            ),
            body: FutureBuilder(
              future: l_orders,
              builder: (BuildContext context, AsyncSnapshot snapshot) {
                if (!snapshot.hasData) {
                  // while data is loading:
                  return Center(
                    child: CircularProgressIndicator(backgroundColor: Colors.red,valueColor: new AlwaysStoppedAnimation<Color>(Colors.blue)),
                  );
                } else {
                  // data loaded:
                 return Text("Test");
                }
              },
            ),
    
            floatingActionButton: FloatingActionButton(
    
              onPressed: (){print('test');},
              child: Icon(Icons.home,size: 40,),
              //backgroundColor: Colors.green,
            ),
            floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
           ),
        );
      }
    } 
    

    l_orders 一个静态类型将帮助您在编译时发现这些错误。不要使用动态的var l_orders;,而是使用Future l_orders;Future&lt;String&gt; l_orders;。另外,请注意all静态分析警告。仅仅因为它们不是错误并不意味着它们无关紧要。

    【讨论】:

    • 嗨,你上面说的很有道理。但是,即使进行了上述更改,我仍然可以看到 CircularProgressIndicator 它永远不会进入完成状态,即我仍然无法在我的屏幕上看到文本“测试”。
    • 谢谢你我接受了你的回答。现在可以使用了
    • 正如 Christopher 在他的编辑中显示的那样,您在 build 方法内有 initState,它需要在外面。
    • 我正在尝试它的解决方案。但是,第一次加载数据时它不起作用
    猜你喜欢
    • 2021-06-17
    • 2023-02-18
    • 2021-08-13
    • 2021-03-04
    • 2021-08-17
    • 1970-01-01
    • 2022-06-21
    • 2021-06-19
    • 2021-05-11
    相关资源
    最近更新 更多