【问题标题】:How to pass data across Stateful widget?如何跨有状态小部件传递数据?
【发布时间】:2021-07-23 00:08:06
【问题描述】:

所以我的问题是我在第一个小部件中从 firebase 获取数据,然后我单击并通过 void 打开底部表 -> 另一个有状态小部件,我如何将快照数据从第一个小部件传递到另一个小部件?

下面的代码不起作用...

....
Widget build(BuildContext context) {
          return Container(
              ElevatedButton(
                    child: Text('Request a tour'),
                    onPressed: () {
                      displayBottomSheet(context, widget.snapshot.data()["author"]);
                    },
                  ),
                );


    void displayBottomSheet(BuildContext context, String author) {  //updated
    showModalBottomSheet(
        context: context,
        builder: (ctx) {
          return BottomSheetWidget(author);  //updated
        });
  }

新错误:位置参数过多:预期为 0,但找到了 1 个。

class BottomSheetWidget extends StatefulWidget {   

     final String author;                 //updated
     BottomSheetWidget({this.author});    //updated

     @override
  class _BottomSheetWidgetState createState() => _BottomSheetWidgetState();
}

class _BottomSheetWidgetState extends State<BottomSheetWidget> {

    Widget build(BuildContext context) {
          return Container(
                  new ElevatedButton(
                  child: Text('Send'),
                  onPressed: () {
                    requestTour(widget.author);     //updated
                  },
                ),
               .....
              }


    requestTour(String userName) async { 
    ...
    }

【问题讨论】:

    标签: firebase flutter flutter-showmodalbottomsheet


    【解决方案1】:
    class BottomSheetWidget extends StatefulWidget {   
    
         final String author;                 //updated
         BottomSheetWidget(this.author);    //<-- remove {}
    
         @override
      class _BottomSheetWidgetState createState() => _BottomSheetWidgetState();
    }
    
    class _BottomSheetWidgetState extends State<BottomSheetWidget> {
    
        Widget build(BuildContext context) {
              return Container(
                      new ElevatedButton(
                      child: Text('Send'),
                      onPressed: () {
                        requestTour(widget.author);     //updated
                      },
                    ),
                   .....
                  }
    
    
        requestTour(String userName) async { 
        ...
        }
    

    【讨论】:

    • 随时好友 ;)
    【解决方案2】:

    只需删除新到达错误的花括号: 将BottomSheetWidget({this.author}); 替换为BottomSheetWidget(this.author);

    【讨论】:

    • 谢谢!成功了!,我可以知道为什么不需要 curly 吗?
    • 当然,我们可以通过多种方式通过 dart 中的参数传递数据。 1. 默认(不带任何大括号),2. 命名(如您所定义 - 带花括号) 3. 可选。所以如果你使用花括号......你需要在传递数据时添加一个名称。 (在本例中:BottomSheetWidget(author: author);)。像所有其他小部件一样,我们正在使用。希望这能给你一个基本的了解。您可以参考这篇文章了解更多信息。 dart.dev/guides/language/language-tour#parameters
    猜你喜欢
    • 2021-08-29
    • 2019-12-29
    • 2019-12-28
    • 2019-07-08
    • 2022-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多