Shamshun
Shamshun

Reputation: 482

How can I add a key property to a widget that doesn't have it already?

I want to assign a GlobalKey to a widget that doesn't have a "key" property by default. I tried to extend the widget class, add a key property, but I couldn't figure it out. (I also read it later that I probably shouldn't extend widget classes).

Problem: I need to get final rendered position of a BottomNavigationBarItem widget (which doesn't accept (key:) ) ; to do so, I can assign a GlobalKey and get position/offsets of widgets (which I already did, for other widgets except these keyless widgies)

Some simple NavigationBar code:

return Scaffold(
  bottomNavigationBar: new BottomNavigationBar(
    key: navbarKey,   //  ---> NavigationBar has a "key" property
    items: [
      BottomNavigationBarItem(
          //  ---> BottomNavBarItem -> I dont have a key property :(
          icon: ImageIcon(images/someimg.png")),
          title: Text("SomeText")),
      BottomNavigationBarItem(.....)
        ]
        ),),

So, how can I do this?

Upvotes: 2

Views: 705

Answers (1)

Shamshun
Shamshun

Reputation: 482

Although I wasn't successful in adding a Key to BottomNavigationBarItem widget, I found out I can add a key to its Icon!

BottomNavigationBarItem(
          icon: ImageIcon(
            AssetImage("images/Icon_BottomBar_learning.png"),
            key: navbarItemIconKey,
), ),

This helps me to draw what I want to draw on roughly the same spot I intended to. I can now use this path:

return Path()
      ..addRect(Rect.fromLTWH(0, 0, size.width, size.height))
      ..addOval(Rect.fromCircle(
              center: navbarItemIconKey.currentContext
                  .findRenderObject()
                  .paintBounds
                  .shift(Offset(
                      navbarItemIconKey.currentContext
                          .findRenderObject()
                          .getTransformTo(null)
                          .getTranslation()
                          .x,
                      navbarItemIconKey.currentContext
                          .findRenderObject()
                          .getTransformTo(null)
                          .getTranslation()
                          .y))
                  .center,
              radius: 40)

Hmmm.

Upvotes: 4

Related Questions