如何调用函数并获取其返回值?颤振/飞镖

时间:2020-05-12 13:39:04

标签: flutter dart

我希望右上角的文字为Total Members: example,但目前我收到Total Members: Instance of 'Future<String>',但不确定为什么

我的代码:

class _MainPageState extends State<MainPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Main",
            style: globals.style
                .copyWith(color: Colors.white, fontWeight: FontWeight.bold)),
      ),
      drawer: MyDrawer(),
      body: Container(
        alignment: Alignment.topRight,
        margin: new EdgeInsets.only(top: 20.0, right: 20.0),
        child: Text('Total Members: ' + fetchMainInfo().toString(),
            style: globals.style
                .copyWith(color: Colors.black, fontWeight: FontWeight.bold)),
      ),
    );
  }
}


Future<String> fetchMainInfo() async {
  return "example";
}

我对扑镖/飞镖很陌生,所以很抱歉,如果答案很明显,但是我已经环顾四周,但找不到适合我的东西,并且找到了一些设置状态的东西但我想知道是否有类似的方法,因为我对飞镖/飞镖很陌生

2 个答案:

答案 0 :(得分:2)

您会遇到此错误,因为您正试图从异步方法中获取数据,因此要解决此问题,您需要futurebuilder。

FutureBuilder(
          future: fetchMainInfo(),
          builder: (_, snapshot) {
            if (snapshot.hasData) {
              return Text('Total Members: ${snapshot.data}',
                  style: globals.style.copyWith(
                      color: Colors.black, fontWeight: FontWeight.bold));
            } else {
              return CircularProgressIndicator();
            }
          }),

答案 1 :(得分:1)

如果您的方法仅返回.alert而不返回struct ContentView: View { @State var errorMessage: String = "" var body: some View { let shouldShowAlert = Binding<Bool>( get: { !self.errorMessage.isEmpty }, set: { if !$0 { self.errorMessage = "" } } ) return Text("Hello, World!") .alert( isPresented: shouldShowAlert, content: { Alert( title: Text("Important message"), message: Text("This is an important message"), dismissButton: .default(Text("Ok") )) }) } } ,则应以其定义为准。从方法中删除StringFuture

Future