1

我是 Flutter 的新手,我正在尝试在sidenavbar. 我陷入了一个代码段。经过几次尝试,我得到了如下错误:

类型 Future 不是 Widget 类型的子类型

我有以下代码。在我的案例 0: 语句中,我应该如何调用 _logOutUser() 函数? 任何帮助将不胜感激

final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;

class Homepage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      routes: {
        '/login': (context) => Login(),
      },
      title: 'NavigationDrawer Demo',
      theme: new ThemeData(
        primarySwatch: Colors.red,
      ),
      home: new HomePage(),
    );
  }
}

class DrawerItem {
  String title;
  IconData icon;
  DrawerItem(this.title, this.icon);
}

class HomePage extends StatefulWidget {
  HomePage({
    this.auth,
    this.onSignedOut,
  });
  final AuthImplementation auth;
  final VoidCallback onSignedOut;
  final drawerItems = [
    new DrawerItem("Logout", Icons.exit_to_app),
  ];

  @override
  State<StatefulWidget> createState() {
    return new HomePageState();
  }
}

class HomePageState extends State<HomePage> {
  void _logOutUser() async {
    try {
      await widget.auth.signOut();
      widget.onSignedOut();
    } catch (e) {
      print(e.toString());
    }
  }

  int _selectedDrawerIndex = 0;
  _getDrawerItemWidget(int pos) {
    switch (pos) {
      case 0:
        return HomePageState()._logOutUser();
      default:
        return new Text("Error");
    }
  }

  _onSelectItem(int index) {
    setState(() => _selectedDrawerIndex = index);
    Navigator.of(context).pop();
  }

  @override
  Widget build(BuildContext context) {
    var drawerOptions = <Widget>[];
    for (var i = 0; i < widget.drawerItems.length; i++) {
      var d = widget.drawerItems[i];
      drawerOptions.add(
          new ListTile(
            leading: new Icon(d.icon),
            title: new Text(d.title),
            selected: i == _selectedDrawerIndex,
            onTap: () => _onSelectItem(i),
          )
      );
    }

  }
}
4

1 回答 1

1

我对你的问题有点困惑,但如果我没记错的话,你为什么不这样做:

switch (pos) {
      case 0:
        HomePageState()._logOutUser();
        return Text("Logged Out");
        // or if you don't want to show anything you could just return a blank Container, or
        // if you wanted to navigate to login screen just use Navigator.push() and return the Container
      default:
        return new Text("Error");
    }

您收到错误的原因type Future<dynamic> is not a subtype of Widget是您的 Function_logOutUser()没有返回 Widget。如果我没有回答您的问题,请在下方评论。

于 2020-03-11T19:58:42.957 回答