0

In Dart, a function cannot be used before it is defined. How can 2 functions call each other? How can I work around with the following code snippet ? The _createComponent function calls _showLayerPopupMenu which has an menu item action to call _createComponent.

void _showLayerPopupMenu(int idx) async {
      var selected = await showMenu(
        context: context,
        position: RelativeRect.fromLTRB(100, 100, 100, 100),
        items: [
          PopupMenuItem(
            child: Text("Merge Down"),
            value: 0,
          ),
          PopupMenuItem(
            child: Text("Duplicate"),
            value: 1,
          ),
         
        ],
        elevation: 8.0,
      );
      if (selected == 0) _mergeLayer(idx);
      if (selected == 1) {
    LayerPainter layerPainter=LayerPainter();
    _createComponent(layerPainter,idx);
    }
    
    }


Widget _createComponent(LayerPainter layerPainter, int id) {
       return Container(
          width: 120,
          height: 160,
          decoration: BoxDecoration(
              color: layerPainter.isColorMask ? Colors.blue : Colors.green,
              borderRadius: new BorderRadius.only(
                topLeft: const Radius.circular(10.0),
                topRight: const Radius.circular(10.0),
              )),
          child: Stack(children: <Widget>[
               IconButton(
                icon: id >= 0
                    ? const Icon(Icons.menu)
                    : Icon(null), //const Icon(Icons.remove),
                onPressed: () {
                  if (id >= 0) _showLayerPopupMenu(id);
                },
              ),
            ]),
      ),
    }
jdevp2
  • 371
  • 5
  • 15
  • put them into two separate dart files and import(reference) each other – user14624595 Feb 25 '21 at 13:29
  • "In Dart, a function cannot be used before it is defined." The premise of this question is wrong. It is no problem to have mutually recursive functions. Please post a minimal, reproducible example of your problem and explain what error you're encountering. – jamesdlin Feb 25 '21 at 18:13
  • @ user14624595 That might be a work around. I'll give it a try. – jdevp2 Feb 25 '21 at 19:21
  • @jamesdlin I should have made it clear that they are the local functions The global functions seem be fine. After posting the question, I found an old question that you responded before at https://stackoverflow.com/questions/64399949/dart-why-local-functions-can-not-call-each-other – jdevp2 Feb 25 '21 at 19:33
  • Ah, I had forgotten about that. (Also, if those are local functions, then there's no point in prefixing their names with `_`.) Why not make them instance methods instead? – jamesdlin Feb 25 '21 at 20:04

0 Answers0