在flutter中使用Future Function和Future builder时如何使用InitState

How to use InitState when using Future Function and Future builder in flutter

我在 Flutter 中遇到问题。我不习惯高效地使用 Future Functions。 我正在尝试从有状态 class 的 InitSate 中的 Future 函数获取值,然后在 Future Builder 中使用 return 值。 但是,当我在 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,
       ),
    );
  }
} 

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

initState 应该如下:

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

此外,您的所有成员和您的 initState 声明都在 build 中。将它们从 build 移到 class.

的正文中
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<String> l_orders;。此外,请注意 all 静态分析警告。仅仅因为它们不是错误并不意味着它们无关紧要。