0

I'm using GetX in Flutter. I'm tired of having to write like this every time in Drawer.


            ListTile(
              title: Text('signIn'),
              onTap: () {
                Get.to(SigninPage());
              },
            ),

So I decided to put them together in a Map like this and then loop with a for statement.

  Map _showWidgets = {
    "Home": () => MyHomePage(),
    "Word": () => WordPage(),
    "Sign In": () => SigninPage(),
    "Sign Up": () => SignupPage(),
    "Writing": () => WritingPage(),
    "Order": () => OrderPage(),
    "Pronounce": () => PronouncePage()
  };
  List get showNames {
    return _showWidgets.keys.toList();
  }

//at Drawer for loop
for (var name in showNames)
  ListTile(
    title: Text(name),
    onTap: () {
      Get.to(_showWidgets[name]);
    },
  ),

But I get an error:

"setState () or markNeedsBuild () called during build."

What's wrong? Is named route the only solution? Is there a good way to create a Drawer with a for loop?

Of course it works fine with this but it's not elegant.

  Map _showWidgets = {
    "Home": () => Get.to(MyHomePage()),
    "Word": () => Get.to(WordPage()),
    "Sign In": () => Get.to(SigninPage()),
    "Sign Up": () => Get.to(SignupPage()),
    "Writing": () => Get.to(WritingPage()),
    "Order": () => Get.to(OrderPage()),
    "Pronounce": () => Get.to(PronouncePage())
  };

Tatsuhiko Mizuno
  • 437
  • 6
  • 15
  • 2
    This error means that you are telling Flutter to rebuild the UI while it is already building the same widget. Usually caused by having listeners and triggers fire together. Solve that in your GetX logic. – Huthaifa Muayyad Aug 09 '21 at 14:30

1 Answers1

1

Try something like this:

Create a method buildDrawerTiles:

List<ListTile> buildDrawerTiles(List<String> showNames){

   List<ListTile> tiles= [];

   for (var name in showNames){
    final tile = ListTile(
      title: Text(name),
      onTap: () {
      Get.to(_showWidgets[name]);
     },
    );

    tiles.add(tile);
  }

  return tiles;
 }

Then on the drawer, call it:

buildDrawerTiles(showNames);
S. M. JAHANGIR
  • 4,324
  • 1
  • 10
  • 30