【问题标题】:Flutter passing data and calling out method from a stateful widget to another statefulwidgetFlutter 从有状态小部件向另一个有状态小部件传递数据和调用方法
【发布时间】:2021-01-22 15:59:16
【问题描述】:

美好的一天!我这里有一些 MainMenu 页面和 Drawer 的代码块。 我需要将 MainMenu 中的数据(它是一个 statefulwidget)传递给 Drawer,它也是一个 statefulwidget,以便我可以使用 MainMenu 中的数据和方法。 有人可以帮助我或在下面重现我的代码。

class MainMenu extends StatefulWidget {

  
  final VoidCallback signOut;

  MainMenu(this.signOut);
  

  @override
  _MainMenuState createState() => _MainMenuState();
}

class _MainMenuState extends State<MainMenu> {

  int index = 0;
 

  List<Widget> list = [
    HomeScreen(),
    Stations(),
    AccountPage(),

    
  ];

  signOut() {
    setState(() {
      widget.signOut();
    });
  }

  int currentIndex = 0;
  String selectedIndex = 'TAB: 0';

  String email = "", id = "", fname= "";
  TabController tabController;

  

  getPref() async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    setState(() {
       id = preferences.getString('id');
       email = preferences.getString('email');
       fname = preferences.getString('fname');
    
    
    });
    print("id:" + id);
    print("user:" + email);
    print("address:" + fname);

  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getPref();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          actions: <Widget>[
          IconButton(
            onPressed: () {
              signOut();
            },
            icon: Icon(Icons.lock_open),
          )
        ],
          backgroundColor: Color(0xFF262AAA),
           iconTheme: IconThemeData(color: Colors.lightBlue),
          centerTitle: true,
        title: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text('DVO',
            style: TextStyle(color: Colors.lightBlue,fontWeight: FontWeight.w700),
            ),
            SizedBox(width: 1.3),
            Text(
              'REPORT',
              style: TextStyle(color: Colors.white,fontWeight: FontWeight.w700),
            ),
          ],
        ),
        elevation: 0,
      ),
        body: list[index],
        drawer:  MyDrawer(onTap: (lol, i) {
          setState(() {
            index = i;
            Navigator.pop(lol);
          });
        }),
      ),
    );
  }
}

class MyDrawer extends StatefulWidget {
    

    @override
  _MyDrawerState createState() => _MyDrawerState();
}

    
 class _MyDrawerState extends State<MyDrawer> { 

   Function onTap;
   _MyDrawerState(
    {this.onTap
    });
  
  

  @override
  Widget build(BuildContext context) {
    
    return SizedBox(
      width: MediaQuery
          .of(context)
          .size
          .width * 0.7,
      child: Drawer(
        child: Container(
          color: Colors.white,
          child: ListView(
            padding: EdgeInsets.all(0),
            children: <Widget>[
              
              UserAccountsDrawerHeader(
                decoration: BoxDecoration(
                color: Colors.white,
                 image: DecorationImage(
                  image: AssetImage("assets/badge.jpg"),
                     fit: BoxFit.cover,
                      colorFilter: new ColorFilter.mode(Colors.black.withOpacity(0.8), BlendMode.dstATop)),
               ),
                accountEmail: Text("dummy@gmail.com"),
                accountName: Text("Dummy", 
                style: TextStyle(color: Colors.white,fontWeight: FontWeight.w700, fontSize: 25),
                ),
                currentAccountPicture: CircleAvatar(
                  backgroundColor: Colors.grey[400],
                  child: Icon(
                            Icons.perm_identity,
                            color: Colors.white,
                  ),
                
                ),
              ),
              ListTile(
                selected: true,
                leading: Icon(Icons.announcement, color: Colors.cyan,size: 26.0),
                title: Text("News And Announcements", 
               
                style: TextStyle(color: Colors.black,fontWeight: FontWeight.w500, fontSize: 18),
                ),
                onTap: () => onTap(context, 0),
                
              ),
              ListTile(
                leading: Icon(Icons.place,color: Colors.cyan, size: 30.0),
                title: Text("Stations",
                style: TextStyle(color: Colors.black,fontWeight: FontWeight.w500, fontSize: 18),
                ),
                onTap: () => onTap(context, 1),
              ),
              ListTile(
                leading: Icon(Icons.settings,color: Colors.cyan, size: 30.0),
                title: Text("Account Settings",
                style: TextStyle(color: Colors.black,fontWeight: FontWeight.w500, fontSize: 18),
                ),
                 onTap: () => onTap(context, 2),
              ),
               Divider(
                        height: 595,
                        thickness: 0.5,
                        color: Colors.white.withOpacity(0.3),
                        indent: 32,
                        endIndent: 32,
                      ),
               ListTile(
                leading: Icon(Icons.exit_to_app,color: Colors.cyan, size: 30.0),
                 onTap: () {
                 //widget.signOut();
                  },
                title: Text("Logout",
                style: TextStyle(color: Colors.black,fontWeight: FontWeight.w500, fontSize: 18),
              
                ),
              ),
         
            ],
          ),
        ),
      ),
    );
  }
}

我在 MainMenu 的构建小部件上收到此错误。

未定义命名参数“onTap”。 尝试将名称更正为现有命名参数的名称,或使用名称“onTap”定义命名参数。

【问题讨论】:

    标签: flutter dart statefulwidget


    【解决方案1】:

    这部分:

    Function onTap;
    
    _MyDrawerState({this.onTap});
    

    这个参数及其在构造函​​数中的存在应该在MyDrawer公共类而不是私有State类中。

    出现指定错误是因为MyDrawer 类没有这个。

    您可以通过widget 变量访问_MyDrawerState 中的onTap 函数,该变量是MyDrawer 类的实例

    【讨论】:

    • 如何访问。对不起,我是菜鸟。谢谢! @Arvind
    • widget.onTap(context, 0)替换出现的onTap(context, 0)
    猜你喜欢
    • 2018-12-04
    • 2021-08-29
    • 2020-07-31
    • 2021-12-15
    • 2021-12-24
    • 2018-09-01
    • 1970-01-01
    • 2021-07-12
    • 2019-09-23
    相关资源
    最近更新 更多