首页 > 解决方案 > 如何将参数传递给 FutureBuilder 中的未来属性函数

问题描述

我的问题是我不知道如何将路由的参数传递给位于 FutureBuilder 中的函数。

请在下面查看我的代码。

class StudyDetailsArguments {
  final String listid;

  StudyDetailsArguments(this.listid);
}

// A widget that extracts the necessary arguments from the ModalRoute.
class ExtractStudyDetails extends StatelessWidget {
  static const routeName = '/studydetails';
  
  @override
  Widget build(BuildContext context) => FutureBuilder(

  // Here I want to pass in the args.listid but I cant figure out how to get it in there
    future: getDetails("cc0e5c1f-02b0-4f4f-9f51-fa70ac7e9c08"),
    builder: (context, snapshot) {
     // here is fine to use the argument
      final StudyDetailsArguments  args = ModalRoute.of(context).settings.arguments;
      if (snapshot.hasData) {
        // Build the widget with data.
        //return Text('hasData: ${snapshot.data}');
        return Scaffold(
            appBar: AppBar(
            title: Text(snapshot.data),
      ),
            body:
            Center(
            child:
            Text('${snapshot.data}'))
              );
            } else {
              // We can show the loading view until the data comes back.
            return Scaffold(
            appBar: AppBar(
              title: Text("Loading..."),
            ),
            body:
            Center(
                child:
                Text('Loading...'))
        );
      }
    },
  );
}

Future<String> getDetails(listid) async {
  var details = "";
  await Firestore.instance
      .collection('list')
      .document(listid)
      .get()
      .then((DocumentSnapshot ds) {
        print(ds.data["title"]);
        // use ds as a snapshot
        details = ds.data["title"];
    return ds.data;
  });
  return details;
}

我想使用这一行 args.listid 而不是 cc0e5c1f-02b0-4f4f-9f51-fa70ac7e9c08 但我似乎无法弄清楚传递参数的方法。我如何将参数值(现在不使用)发送到小部件是在小部件中的这种方式:

 onTap: () => {
                    Navigator.pushNamed(context, ExtractStudyDetails.routeName,
                        arguments: StudyDetailsArguments(
                          study.listid,
                        ))
                  },

标签: flutterdart

解决方案


@override
Widget build(BuildContext context) {
  
  final StudyDetailsArguments args = ModalRoute.of(context).settings.arguments;

  return FutureBuilder(
    future: getDetails(args.listid),
    [...]
  )
}

阅读更多关于文档


推荐阅读