如何获得FutureBuilder返回值到变量?

时间:2019-02-22 04:47:25

标签: dart flutter

如何从FutureBuilder获取X值?

final url = FutureBuilder<List<Url>>(
    future: getUrlFromCache(),
    builder: (context,snapshot){var x = snapshot.data[1].uniform_resource_locator;},
    );

2 个答案:

答案 0 :(得分:0)

签出:FutureBuilder

您可以初始化一个全局变量,然后在FutureBuilder中分配一个值,但是我不知道在FutureBuilder中这样做是一个很好的方法。

// instead of creating dynamic types try to create static types.
var x; 

FutureBuilder<String>(
  future: _calculation, // a previously-obtained Future<String> or null
  builder: (context, snapshot) {
    switch (snapshot.connectionState) {
      case ConnectionState.none:
        return Text('Press button to start.');
      case ConnectionState.active:
      case ConnectionState.waiting:
        return Text('Awaiting result...');
      case ConnectionState.done:
        if (snapshot.hasError)
          return Text('Error: ${snapshot.error}');
        x = snapshot.data[1].uniform_resource_locator;
        return Text('Result: ${snapshot.data}');
    }
    return null; // unreachable
  },
)

答案 1 :(得分:0)

我认为使用“ x”将导致“ x”始终等于“ null”。可以通过这种方式动态返回它:

return ListTile(

            title: FutureBuilder(
              future: pair,
              builder: (context, snapshot) {
                if (snapshot.hasData) {
                  return Text( snapshot.data.title);
                } else {
                  return Text( 'Loading...');
                }
              },
            ),

          );

FutureBuilder始终返回Widget类型。将您的功能放在FutureBuilder中。 就我而言,它返回Text小部件。它被分配给“ title:”,并作为ListTile动态显示在屏幕上。 只需将Text小部件替换为将使用数据的必需widget