Search code examples
flutterdartnavigation-drawer

The element type 'Set<UserAccountsDrawerHeader>' can't be assigned to the list type 'Widget'


I create a menu where the header changes depending on whether the user is registered or not. I wrote a condition that if there is such a user, then show a UserAccountsDrawerHeader, if not - DrawerHeader. But I have an error - The element type 'Set' can't be assigned to the list type 'Widget' and The element type 'Set' can't be assigned to the list type 'Widget'. How to write correctly. Please, help

class _AppDrawerState extends State<AppDrawer> {
  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
  var current_user;
  Future<void> _handleDrawer()async{
    _scaffoldKey.currentState.openEndDrawer();
  }

  @override
  Widget build(BuildContext context) {
    return Drawer(
      child: ListView(
        padding: EdgeInsets.zero,
        children: <Widget>[
          if(current_user) {
            return UserAccountsDrawerHeader(
              accountName: new Text("Cleudice Santos"),
              accountEmail: new Text("cleudice.ms@gmail.com"),
              onDetailsPressed: () {},
            ),
          } else {
            return DrawerHeader(
            child: Text('Drawer Header'),
            decoration: BoxDecoration(
            color: Colors.blue,
            ),
            ),
          };
          ListTile(
            leading: Icon(Icons.search),
            title: Text('search1'),
            onTap: () {
            },
          ),
          ListTile(
            leading: Icon(Icons.local_shipping),
            title: Text('search1'),
            onTap: () {
              // Update the state of the app.
              // ...
            },
          ),   
        ],
      ),
    );
  }
}

Solution

  • You cannot explicitly write if condition if <Widget> list unless you use a ListBuilder. You can change you code like this

    Drawer(
      child: ListView(
        padding: EdgeInsets.zero,
        children: <Widget>[
          current_user ? UserAccountsDrawerHeader(
            accountName: new Text("Cleudice Santos"),
            accountEmail: new Text("cleudice.ms@gmail.com"),
            onDetailsPressed: () {},
          ) : DrawerHeader(
            child: Text('Drawer Header'),
            decoration: BoxDecoration(
              color: Colors.blue,
            ),
          ),
          ListTile(
            leading: Icon(Icons.search),
            title: Text('search1'),
            onTap: () {
            },
          ),
          ListTile(
            leading: Icon(Icons.local_shipping),
            title: Text('search1'),
            onTap: () {
              // Update the state of the app.
              // ...
            },
          ),
        ],
      ),
    )