Flutter传递数据并从有状态的小部件向另一个有状态的小部件调出方法

时间:2020-10-07 16:29:28

标签: flutter dart statefulwidget

美好的一天!我的MainMenu页面和抽屉中有一些代码块。 我需要将数据从MainMenu(这是一个有状态的小部件)传递到Drawer(也是有状态的小部件),以便可以使用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”的命名参数。

1 个答案:

答案 0 :(得分:0)

此部分:

Function onTap;

_MyDrawerState({this.onTap});

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

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

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