Home > Blockchain >  Flutter: How to use Drawer dynamically?
Flutter: How to use Drawer dynamically?

Time:08-13

The "fetchMenus()" method retrieves list of names. I want to use these names in Text of ListTile . How can i do that?

This is my model Class:

class Menu {
  const Menu({
    required this.name,
    required this.folder,
  });

  final String name;
  final String folder;

  factory Menu.fromJson(Map<String, dynamic> json) => Menu(
    name: json["name"],
    folder: json["folder"],
  );

  Map<String, dynamic> toJson() => {
    "name": name,
    "folder": folder,
  };
}

This is my code which is making request to api:

 Future<List<Menu>> fetchMenus() async {
      final response =
          await http.get(Uri.parse('http://myUrl:3355/'));
      if (response.statusCode == 200) {
        var getMenusData = json.decode(response.body) as List;
        var listMenus = getMenusData.map((i) => Menu.fromJson(i)).toList();
        return listMenus;
      } else {
        throw Exception('Failed to load Menus');
      }
    }

And the code I want to change;

Drawer(
  child: ListView(
    padding: EdgeInsets.zero,
    children: [
      const DrawerHeader(
        decoration: BoxDecoration(
          color: Colors.blue,
        ),
        child: Text('Drawer Header'),
      ),
      ListTile(
        title: const Text('Item 1'),
        onTap: () {
        },
      ),
      ListTile(
        title: const Text('Item 2'),
        onTap: () {
        },
      ),
    ],
  ),
);

CodePudding user response:

You can use the FutureBuilder widget to fetch your menu names and then build the corresponding list tiles. Something like this:

FutureBuilder<List<Menu>>(
      future: fetchMenus(),
      builder: (context, snapshot) {
        return ListView(
          padding: EdgeInsets.zero,
          children: [
            const DrawerHeader(
              decoration: BoxDecoration(
                color: Colors.blue,
              ),
              child: Text('Drawer Header'),
            ),
            ListTile(
              title: Text(snapshot.data![0].name),
              onTap: () {},
            ),
            ListTile(
              title: Text(snapshot.data![1].name),
              onTap: () {},
            ),
          ],
        );
      },
    )

CodePudding user response:

Create a method which build your tiles and call this method in your listview:

Drawer(
  child: ListView(
    padding: EdgeInsets.zero,
    children: [
      const DrawerHeader(
        decoration: BoxDecoration(
          color: Colors.blue,
        ),
        child: Text('Drawer Header'),
      ),
      _buildTiles()
    ],
  ),
);

The _buildTiles method:

List<Widget> _buildTiles(){
    List<Widget> tiles;

    for ( Menu menu in menus )
    {
        tiles.add( ListTile(
        title: const Text(menu.name),
        onTap: () {
        },
      ));
    }
    
    return tiles;
}

assuming you store you items in a menus var.

  • Related