build method

  1. @override
Widget build(
  1. BuildContext context
)
override

Describes the part of the user interface represented by this widget.

The framework calls this method when this widget is inserted into the tree in a given BuildContext and when the dependencies of this widget change (e.g., an InheritedWidget referenced by this widget changes). This method can potentially be called in every frame and should not have any side effects beyond building a widget.

The framework replaces the subtree below this widget with the widget returned by this method, either by updating the existing subtree or by removing the subtree and inflating a new subtree, depending on whether the widget returned by this method can update the root of the existing subtree, as determined by calling Widget.canUpdate.

Typically implementations return a newly created constellation of widgets that are configured with information from this widget's constructor and from the given BuildContext.

The given BuildContext contains information about the location in the tree at which this widget is being built. For example, the context provides the set of inherited widgets for this location in the tree. A given widget might be built with multiple different BuildContext arguments over time if the widget is moved around the tree or if the widget is inserted into the tree in multiple places at once.

The implementation of this method must only depend on:

If a widget's build method is to depend on anything else, use a StatefulWidget instead.

See also:

  • StatelessWidget, which contains the discussion on performance considerations.

Implementation

@override
Widget build(BuildContext context) {
  Widget widget = Text(statement.toScript());
  String label;
  IconData? iconData;
  bool isStatementBlock = false;
  bool canEdit = canChange;

  /// Use maybeOf here as it becomes null when the StatementWidget is being reordered,
  /// at which point it is in a different BuildContext and no longer has access to
  /// the NeoTechInheritedWidget.
  final neoTechCoreInheritedWidget = DartBlockEditorInheritedWidget.maybeOf(
    context,
  );
  DartBlockException? neoTechException =
      neoTechCoreInheritedWidget?.executor.thrownException;
  Widget? exceptionWidget =
      neoTechException != null &&
          neoTechException.statement != null &&
          // Warning: do not use hashCode of statement here - because the
          /// program execution happens in an isolate, the thrown NeoTechException's
          /// 'statement' field is in fact a copy and thus no longer has the
          /// same hashCode.
          neoTechException.statement!.statementId == statement.statementId
      ? PopupWidgetButton(
          tooltip: "Exception",
          width: MediaQuery.of(context).size.width * 0.9,
          onOpened: () {
            DartBlockInteraction.create(
              dartBlockInteractionType: DartBlockInteractionType
                  .tapExceptionIndicatorOnCausingStatement,
              content: "ExceptionTitle-${neoTechException.title}",
            ).dispatch(context);
          },
          widget: DartBlockExceptionWidget(
            dartblockException: neoTechException,
            program: neoTechCoreInheritedWidget?.program,
          ),
          child: Icon(
            Icons.error,
            color: Theme.of(context).colorScheme.error,
          ),
        )
      : null;
  switch (statement) {
    case StatementBlock():
      label = "Block";
      isStatementBlock = true;
      break;
    case ForLoopStatement():
      label = "For-Loop";
      iconData = Icons.loop;
      isStatementBlock = true;
      widget = ForLoopStatementWidget(
        statement: statement as ForLoopStatement,
        canDelete: canDelete,
        canChange: canChange,
        canReorder: canReorder,
        onChanged: onChanged,
        onCopiedStatement: onCopiedStatement,
        onPastedStatement: onPastedStatement,
        customFunctions: customFunctions,
        displayToolboxItemDragTarget:
            neoTechCoreInheritedWidget?.isDraggingToolboxItem.value ?? false,
      );
      break;
    case WhileLoopStatement():
      final whileLoopStatement = statement as WhileLoopStatement;
      iconData = Icons.loop;
      label = whileLoopStatement.isDoWhile ? "Do-While-Loop" : "While-Loop";
      isStatementBlock = true;
      widget = WhileLoopStatementWidget(
        statement: statement as WhileLoopStatement,
        canDelete: canDelete,
        canChange: canChange,
        canReorder: canReorder,
        onChanged: onChanged,
        onCopiedStatement: onCopiedStatement,
        onPastedStatement: onPastedStatement,
        customFunctions: customFunctions,
        displayToolboxItemDragTarget:
            neoTechCoreInheritedWidget?.isDraggingToolboxItem.value ?? false,
      );
      break;
    case PrintStatement():
      label = "Print";
      widget = PrintStatementWidget(statement: statement as PrintStatement);
      break;
    case ReturnStatement():
      label = "Return";
      widget = ReturnStatementWidget(statement: statement as ReturnStatement);
      break;
    case VariableDeclarationStatement():
      label = "Declare";
      widget = VariableDeclarationStatementWidget(
        statement: statement as VariableDeclarationStatement,
      );
      break;
    case VariableAssignmentStatement():
      label = "Update";
      widget = VariableAssignmentStatementWidget(
        statement: statement as VariableAssignmentStatement,
      );
      break;
    case IfElseStatement():
      label = "If-Then-Else";
      iconData = Icons.alt_route_sharp;
      isStatementBlock = true;
      widget = IfElseStatementWidget(
        statement: statement as IfElseStatement,
        canDelete: canDelete,
        canChange: canChange,
        canReorder: canReorder,
        onChanged: onChanged,
        onCopiedStatement: onCopiedStatement,
        onPastedStatement: onPastedStatement,
        customFunctions: customFunctions,
        displayToolboxItemDragTarget:
            neoTechCoreInheritedWidget?.isDraggingToolboxItem.value ?? false,
      );
      break;
    case FunctionCallStatement():
      label = "Call";
      final customFunctionCallStatement = statement as FunctionCallStatement;
      widget = FunctionCallStatementWidget(
        statement: customFunctionCallStatement,
        customFunction: customFunctions.firstWhereOrNull(
          (element) =>
              element.name == customFunctionCallStatement.customFunctionName,
        ),
      );
      break;
    case BreakStatement():
      label = "Break";
      canEdit = false;
      widget = BreakStatementWidget(statement: statement as BreakStatement);
      break;
    case ContinueStatement():
      label = "Continue";
      canEdit = false;
      widget = ContinueStatementWidget(
        statement: statement as ContinueStatement,
      );
      break;
  }

  return Padding(
    padding: EdgeInsets.only(bottom: includeBottomPadding ? 8 : 0),
    child: InkWell(
      onTapUp: (TapUpDetails details) async {
        DartBlockInteraction.create(
          dartBlockInteractionType: DartBlockInteractionType.tapStatement,
          content:
              'StatementType-${statement.statementType.name}-StatementId-${statement.statementId}${exceptionWidget != null ? '-CausedException' : ''}',
        ).dispatch(context);

        /// Use maybeOf rather of here, as the user may have been dragging
        /// the statement and the drop animation has not yet finished.
        /// If the animation has not finished, the context will not find the NeoTechCoreInheritedWidget.
        final neoTechCoreInheritedWidget =
            DartBlockEditorInheritedWidget.maybeOf(context);
        final RenderBox overlay =
            Overlay.of(context).context.findRenderObject() as RenderBox;
        if (neoTechCoreInheritedWidget != null) {
          _showMoreOptions(
            context,
            position: RelativeRect.fromRect(
              details.globalPosition & const Size(40, 40),
              Offset.zero & overlay.size,
            ),
            canEdit: canEdit,
            canCopy: canChange,
            canDelete: canDelete,
            canDuplicate: canChange && canDuplicate,
            canPaste:
                canChange &&
                neoTechCoreInheritedWidget.copiedStatement != null,
          ).then((selectedOption) {
            if (selectedOption != null) {
              if (context.mounted) {
                switch (selectedOption) {
                  case 'edit':
                    DartBlockInteraction.create(
                      dartBlockInteractionType:
                          DartBlockInteractionType.editStatement,
                      content:
                          'StatementType-${statement.statementType.name}-StatementId-${statement.statementId}${exceptionWidget != null ? '-CausedException' : ''}',
                    ).dispatch(context);
                    final existingVariableDefinitions =
                        neoTechCoreInheritedWidget.program
                            .buildTree()
                            .findVariableDefinitions(
                              statement.hashCode,
                              includeNode: false,
                            );
                    StatementEditor.edit(
                      statement: statement,
                      existingVariableDefinitions:
                          existingVariableDefinitions,
                      customFunctions:
                          neoTechCoreInheritedWidget.program.customFunctions,
                      onSaved: (value) {
                        DartBlockInteraction.create(
                          dartBlockInteractionType:
                              DartBlockInteractionType.editedStatement,
                          content:
                              'StatementType-${statement.statementType.name}-StatementId-${statement.statementId}${exceptionWidget != null ? '-CausedException' : ''}',
                        ).dispatch(context);
                        Navigator.of(context).pop();
                        ScaffoldMessenger.of(context).showSnackBar(
                          createDartBlockInfoSnackBar(
                            context,
                            iconData: Icons.check,
                            message:
                                "Saved '${value.statementType.toString()}' statement.",
                          ),
                        );
                        onChanged(value);
                      },
                    ).showAsModalBottomSheet(context);
                  case 'cut':
                    DartBlockInteraction.create(
                      dartBlockInteractionType:
                          DartBlockInteractionType.cutStatement,
                      content:
                          'StatementType-${statement.statementType.name}-StatementId-${statement.statementId}${exceptionWidget != null ? '-CausedException' : ''}',
                    ).dispatch(context);
                    onCopyStatement(statement, true);
                    break;
                  case 'copy':
                    DartBlockInteraction.create(
                      dartBlockInteractionType:
                          DartBlockInteractionType.copyStatement,
                      content:
                          'StatementType-${statement.statementType.name}-StatementId-${statement.statementId}${exceptionWidget != null ? '-CausedException' : ''}',
                    ).dispatch(context);
                    onCopyStatement(statement, false);
                    break;
                  case 'paste':
                    if (neoTechCoreInheritedWidget.copiedStatement != null) {
                      DartBlockInteraction.create(
                        dartBlockInteractionType: DartBlockInteractionType
                            .pasteStatementOnExistingStatement,
                      ).dispatch(context);
                      onPasteStatement(
                        neoTechCoreInheritedWidget.copiedStatement!,
                      );
                    }
                    break;
                  case 'duplicate':
                    DartBlockInteraction.create(
                      dartBlockInteractionType:
                          DartBlockInteractionType.duplicateStatement,
                      content:
                          'StatementType-${statement.statementType.name}-StatementId-${statement.statementId}${exceptionWidget != null ? '-CausedException' : ''}',
                    ).dispatch(context);
                    onDuplicate(statement);
                    ScaffoldMessenger.of(context).showSnackBar(
                      createDartBlockInfoSnackBar(
                        context,
                        iconData: Icons.copy,
                        message:
                            "Duplicated '${statement.statementType.toString()}' statement.",
                      ),
                    );
                    break;
                  case 'delete':
                    DartBlockInteraction.create(
                      dartBlockInteractionType:
                          DartBlockInteractionType.deleteStatement,
                      content:
                          'StatementType-${statement.statementType.name}-StatementId-${statement.statementId}${exceptionWidget != null ? '-CausedException' : ''}',
                    ).dispatch(context);
                    onDelete(statement);
                    ScaffoldMessenger.of(context).showSnackBar(
                      createDartBlockInfoSnackBar(
                        context,
                        iconData: Icons.delete,
                        message:
                            "Deleted '${statement.statementType.toString()}' statement.",
                        backgroundColor: Theme.of(
                          context,
                        ).colorScheme.errorContainer,
                        color: Theme.of(context).colorScheme.onErrorContainer,
                      ),
                    );
                    break;
                }
              }
            }
          });
        }
      },
      child: isStatementBlock
          ? Card(
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(12),
                side: BorderSide(
                  color: Theme.of(context).colorScheme.outline,
                ),
              ),
              elevation: 8,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                mainAxisSize: MainAxisSize.min,
                children: [
                  Container(
                    padding: const EdgeInsets.symmetric(vertical: 4),
                    decoration: BoxDecoration(
                      border: Border(
                        bottom: BorderSide(
                          color: Theme.of(context).colorScheme.outline,
                        ),
                      ),
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        if (iconData != null)
                          Padding(
                            padding: const EdgeInsets.only(right: 4),
                            child: Icon(iconData, size: 14),
                          ),
                        Flexible(
                          child: Text(
                            label,
                            style: Theme.of(context).textTheme.bodySmall,
                          ),
                        ),
                      ],
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.symmetric(
                      vertical: 8,
                      horizontal: 8,
                    ),
                    child: widget,
                  ),
                ],
              ),
            )
          : ToolboxDragTarget(
              isEnabled: onAppendNewStatement != null,
              neoTechCoreNodeKey: statement.hashCode,
              isToolboxItemBeingDragged:
                  neoTechCoreInheritedWidget?.isDraggingToolboxItem,
              onSaved: (newStatement) {
                // Navigator.of(context).pop();
                if (onAppendNewStatement != null) {
                  onAppendNewStatement!(newStatement);
                }
              },
              builder: (p0, candidateData, p2) {
                return Stack(
                  children: [
                    Row(
                      children: [
                        if (exceptionWidget != null) ...[
                          exceptionWidget,
                          const SizedBox(width: 4),
                        ],
                        if (showLabel) ...[
                          _buildLabel(context, label),
                          const SizedBox(width: 4),
                        ],
                        Expanded(
                          child: SingleChildScrollView(
                            scrollDirection: Axis.horizontal,
                            child: widget,
                          ),
                        ),
                      ],
                    ),
                    if (candidateData.isNotEmpty)
                      Positioned.fill(
                        child: Container(
                          decoration: BoxDecoration(
                            color: Theme.of(context)
                                .colorScheme
                                .primaryContainer
                                .withValues(alpha: 0.9),
                          ),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              Icon(
                                Icons.format_list_bulleted_add,
                                color: Theme.of(
                                  context,
                                ).colorScheme.onPrimaryContainer,
                              ),
                              const SizedBox(width: 4),
                              Flexible(
                                child: FittedBox(
                                  child: Text(
                                    candidateData.first!.describeAdd(),
                                    style: Theme.of(context)
                                        .textTheme
                                        .bodyMedium
                                        ?.apply(
                                          color: Theme.of(
                                            context,
                                          ).colorScheme.onPrimaryContainer,
                                        ),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                  ],
                );
              },
            ),
    ),
  );
}