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 in a number of different situations. For example:

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, the given BuildContext, and the internal state of this State object.

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. The BuildContext argument is always the same as the context property of this State object and will remain the same for the lifetime of this object. The BuildContext argument is provided redundantly here so that this method matches the signature for a WidgetBuilder.

Design discussion

Why is the build method on State, and not StatefulWidget?

Putting a Widget build(BuildContext context) method on State rather than putting a Widget build(BuildContext context, State state) method on StatefulWidget gives developers more flexibility when subclassing StatefulWidget.

For example, AnimatedWidget is a subclass of StatefulWidget that introduces an abstract Widget build(BuildContext context) method for its subclasses to implement. If StatefulWidget already had a build method that took a State argument, AnimatedWidget would be forced to provide its State object to subclasses even though its State object is an internal implementation detail of AnimatedWidget.

Conceptually, StatelessWidget could also be implemented as a subclass of StatefulWidget in a similar manner. If the build method were on StatefulWidget rather than State, that would not be possible anymore.

Putting the build function on State rather than StatefulWidget also helps avoid a category of bugs related to closures implicitly capturing this. If you defined a closure in a build function on a StatefulWidget, that closure would implicitly capture this, which is the current widget instance, and would have the (immutable) fields of that instance in scope:

// (this is not valid Flutter code)
class MyButton extends StatefulWidgetX {
  MyButton({super.key, required this.color});

  final Color color;

  @override
  Widget build(BuildContext context, State state) {
    return SpecialWidget(
      handler: () { print('color: $color'); },
    );
  }
}

For example, suppose the parent builds MyButton with color being blue, the $color in the print function refers to blue, as expected. Now, suppose the parent rebuilds MyButton with green. The closure created by the first build still implicitly refers to the original widget and the $color still prints blue even through the widget has been updated to green; should that closure outlive its widget, it would print outdated information.

In contrast, with the build function on the State object, closures created during build implicitly capture the State instance instead of the widget instance:

class MyButton extends StatefulWidget {
  const MyButton({super.key, this.color = Colors.teal});

  final Color color;
  // ...
}

class MyButtonState extends State<MyButton> {
  // ...
  @override
  Widget build(BuildContext context) {
    return SpecialWidget(
      handler: () { print('color: ${widget.color}'); },
    );
  }
}

Now when the parent rebuilds MyButton with green, the closure created by the first build still refers to State object, which is preserved across rebuilds, but the framework has updated that State object's widget property to refer to the new MyButton instance and ${widget.color} prints green, as expected.

See also:

  • StatefulWidget, which contains the discussion on performance considerations.

Implementation

@override
Widget build(BuildContext context) {
  // Update the rolesProvider to get the latest inputs.

  updateVariablesProvider(ref);

  // Retrieve the list of inputs as the label and value of the dropdown menu.

  List<String> inputs = getInputs(ref);

  Map typeState = ref.read(typesProvider.notifier).state;

  // Sort the inputs list with numerical types first.

  inputs.sort((a, b) {
    final aType = typeState[a];
    final bType = typeState[b];

    if (aType == Type.numeric && bType != Type.numeric) {
      return -1;
    } else if (aType != Type.numeric && bType == Type.numeric) {
      return 1;
    } else {
      return 0;
    }
  });

  // Retrieve the current selected variable and use that as the initial value
  // for the dropdown menu. If there is no current value and we do have inputs
  // then we choose the first input variable.

  String selected = ref.watch(selectedProvider);
  if (selected == 'NULL' && inputs.isNotEmpty) {
    selected = inputs.first;
  }

  // Retrieve the categoric variables that will be used to group the
  // visualisations by. Be sure to also include the Target. We don;t want to
  // include the IGNORED or IDENT variables.

  List<String> cats = getCategoric(ref);

  // Add a "None" option to the top.

  cats.insert(0, 'None');

  String groupBy = ref.watch(groupByProvider);

  // By default, choose the target variable assume target exists.

  if (groupBy == 'NULL') {
    groupBy = getTarget(ref);
  }

  // BUILD Action.

  void buildAction() {
    // Business logic for building a tree.

    // Run the R scripts.

    // Check if no grouping variable is selected. This can happen if the user
    // explicitly selects 'None', if the provider's initial state 'NULL' is
    // still active, or potentially if it's an empty string.

    if (ref.read(typesProvider.notifier).state[selected] == Type.numeric) {
      if (groupBy == 'None' || groupBy == 'NULL' || groupBy.isEmpty) {
        rSource(context, ref, ['explore_visual_numeric_nogroupby']);
      } else {
        rSource(context, ref, ['explore_visual_numeric']);
      }
    } else {
      if (groupBy == 'None' || groupBy == 'NULL' || groupBy.isEmpty) {
        rSource(context, ref, ['explore_visual_categoric_nogroupby']);
      } else {
        rSource(context, ref, ['explore_visual_categoric']);
      }
    }
  }

  return Column(
    spacing: configRowSpace,
    children: [
      configTopGap,
      Row(
        spacing: configWidgetSpace,
        children: [
          configLeftGap,
          ActivityButton(
            tooltip: '''

            Tap here to generate all of the available plots.

            ''',
            pageControllerProvider:
                visualPageControllerProvider, // Optional navigation
            onPressed: () {
              // Update the providers before building.
              // Had to update here because
              // Unhandled Exception: Tried to modify a provider while the widget tree was building.
              // If you are encountering this error, chances are you tried to modify a provider
              // in a widget life-cycle, such as but not limited to:
              // - build
              // - initState
              // - dispose
              // - didUpdateWidget
              // - didChangeDependencies

              // Modifying a provider inside those life-cycles is not allowed, as it could
              // lead to an inconsistent UI state. For example, two widgets could listen to the
              // same provider, but incorrectly receive different states.

              // To fix this problem, you have one of two solutions:
              // - (preferred) Move the logic for modifying your provider outside of a widget
              //   life-cycle. For example, maybe you could update your provider inside a button's
              //   onPressed instead.

              // - Delay your modification, such as by encapsulating the modification
              //   in a `Future(() {...})`.
              //   This will perform your update after the widget tree is done building

              ref.read(selectedProvider.notifier).state = selected;
              ref.read(groupByProvider.notifier).state = groupBy;

              buildAction();
            },
            child: const Text('Generate Plots'),
          ),
          MarkdownTooltip(
            message: '''

            **Variable:** Choose from amongst the available **Input**
            variables one that is to be visualised.

            ''',
            child: DropdownMenu(
              label: const Text('Variable'),
              width: 200,
              initialSelection: selected,
              dropdownMenuEntries: inputs.map((s) {
                return DropdownMenuEntry(value: s, label: s);
              }).toList(),

              // On selection, record the variable that was selected AND rebuild
              // the visualisations.
              onSelected: (String? value) {
                ref.read(selectedProvider.notifier).state =
                    value ?? 'IMPOSSIBLE';
                // NOT YET WORKING FIRST TIME buildAction();
              },
            ),
          ),
          MarkdownTooltip(
            message: '''

            **Group By:** Choose from amongst the available **Categoric**
            variables one variable by which you wish to group the data. The
            dataset will then be grouped by the values of that chosen variable
            and the distribution of the chosen Variable by these groups will
            be displayed. Choose **None** to not perform any group by.

            ''',
            child: DropdownMenu(
              label: const Text('Group by'),
              width: 200.0,
              initialSelection: groupBy,
              dropdownMenuEntries: cats.map((s) {
                return DropdownMenuEntry(value: s, label: s);
              }).toList(),

              // On selection, record the variable that was selected AND
              // rebuild the visualisations.
              onSelected: (String? value) {
                ref.read(groupByProvider.notifier).state =
                    value ?? 'IMPOSSIBLE';

                // NOT YET WORKING FIRST TIME buildAction();
              },
            ),
          ),
          LabelledCheckbox(
            label: 'Ignore Missing Group by',
            tooltip: '''

            **Ignore Missing Group by:** When selected (the default) then if
            the **Group By** variable has any missing (*NA*) values we will
            ignore them in the plot. If you unslected this option then if the
            variable has missing values, that will be treated as another group
            and displayed in the plots.

            ''',
            provider: ignoreMissingGroupByProvider,
          ),
          LabelledCheckbox(
            label: 'Box Plot Notch',
            tooltip: '''

            **Box Plot Notch:** When selected (the default) this option adds
            notches to the box plots.  The notches represent the confidence
            interval around the median.  This helps in visually assessing if
            two medians are significantly different.

            - **On:** Adds notches to the box plot.

            - **Off:** Displays box plots without notches.

            Note: If the notch areas of two box plots do not overlap, their
            medians are significantly different at approximately a 5%
            significance level.

            For some datasets the notches can not be calculated and so turning
            them off produces a better looking plot.

            ''',
            provider: exploreVisualBoxplotNotchProvider,
          ),
        ],
      ),
    ],
  );
}