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) {
  // Keep the value of text field.

  _minSplitController.text =
      ref.read(treeMinSplitProvider.notifier).state.toString();
  _maxDepthController.text =
      ref.read(treeMaxDepthProvider.notifier).state.toString();
  _minBucketController.text =
      ref.read(treeMinBucketProvider.notifier).state.toString();
  _complexityController.text =
      ref.read(treeComplexityProvider.notifier).state.toString();
  _priorsController.text =
      ref.read(treePriorsProvider.notifier).state.toString();
  _lossMatrixController.text =
      ref.read(treeLossMatrixProvider.notifier).state.toString();

  AlgorithmType selectedAlgorithm =
      ref.read(treeAlgorithmProvider.notifier).state;

  return Container(
    padding: const EdgeInsets.all(16.0),
    child: Column(
      spacing: configRowSpace,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // Algorithm Radio Buttons.
        Row(
          spacing: configWidgetSpace,
          children: [
            ActivityButton(
              key: const Key('build_decision_tree_button'),
              pageControllerProvider:
                  treePageControllerProvider, // Optional navigation

              onPressed: () async {
                // TODO 20240926 gjw SPLIT THIS INTO OWN LOCAL FUNCTION

                // Perform manual validation.

                String? minSplitError = validateInteger(
                  _minSplitController.text,
                  min: 0,
                );
                String? maxDepthError = validateInteger(
                  _maxDepthController.text,
                  min: 1,
                );
                String? minBucketError = validateInteger(
                  _minBucketController.text,
                  min: 1,
                );
                String? complexityError = validateDecimal(
                  _complexityController.text,
                );
                String? priorsError = _validatePriors(_priorsController.text);
                String? lossMatrixError = _validateLossMatrix(
                  _lossMatrixController.text,
                );

                // Collect all errors.

                List<String> errors = [
                  if (minSplitError != null) 'Min Split: $minSplitError',
                  if (maxDepthError != null) 'Max Depth: $maxDepthError',
                  if (minBucketError != null) 'Min Bucket: $minBucketError',
                  if (complexityError != null) 'Complexity: $complexityError',
                  if (priorsError != null) 'Priors: $priorsError',
                  if (lossMatrixError != null)
                    'Loss Matrix: $lossMatrixError',
                ];

                // Check if there are any errors.

                if (errors.isNotEmpty) {
                  // Show a warning dialog if validation fails.

                  showDialog(
                    context: context,
                    builder: (context) => AlertDialog(
                      title: const Text('Validation Error'),
                      content: Text(
                        'Please ensure all input fields are valid before building '
                        'the decision tree:\n\n${errors.join('\n')}',
                      ),
                      actions: [
                        TextButton(
                          onPressed: () {
                            Navigator.of(context).pop();
                          },
                          child: const Text('OK'),
                        ),
                      ],
                    ),
                  );

                  return;
                }

                // 20241215 gjw Require a target variable. This needs to be a
                // function and used across all predictive modelling fetures.

                if (getTarget(ref) == 'NULL') {
                  showOk(
                    context: context,
                    title: 'No Target Specified',
                    content: '''

                  Please choose a variable from amongst those variables in the
                  dataset as the **Target** for the model. You can do this
                  from the **Dataset** tab's **Roles** feature. When building
                  a predictive model, like a decision tree, we need a target
                  variable that we will model so that we can predict its
                  value.

                  ''',
                  );
                } else {
                  // Update provider value.

                  ref.read(treeMinSplitProvider.notifier).state = int.parse(
                    _minSplitController.text,
                  );
                  ref.read(treeMaxDepthProvider.notifier).state = int.parse(
                    _maxDepthController.text,
                  );
                  ref.read(treeMinBucketProvider.notifier).state = int.parse(
                    _minBucketController.text,
                  );

                  ref.read(treeComplexityProvider.notifier).state =
                      double.parse(_complexityController.text);

                  ref.read(treePriorsProvider.notifier).state =
                      _priorsController.text;

                  ref.read(treeLossMatrixProvider.notifier).state =
                      _lossMatrixController.text;

                  ref.read(treeAlgorithmProvider.notifier).state =
                      selectedAlgorithm;

                  // Run the R scripts.

                  String mt = 'model_template';
                  String mbc = 'model_build_ctree';
                  String mbr = 'model_build_rpart';

                  if (selectedAlgorithm == AlgorithmType.conditional) {
                    await rSource(context, ref, [mt, mbc]);
                    ref.read(cTreeEvaluateProvider.notifier).state = true;
                  } else {
                    await rSource(context, ref, [mt, mbr]);
                    ref.read(rpartTreeEvaluateProvider.notifier).state = true;
                  }

                  // Update the state to make the tree evaluate tick box
                  // automatically selected after the model build.

                  ref.read(treeEvaluateProvider.notifier).state = true;
                }
              },
              child: const Text('Build Decision Tree'),
            ),
            Text('Target: ${getTarget(ref)}'),
            ChoiceChipTip<AlgorithmType>(
              options: AlgorithmType.values,
              getLabel: (AlgorithmType type) => type.displayName,
              selectedOption: selectedAlgorithm,
              tooltips: decisionTreeTooltips,
              onSelected: (AlgorithmType? selected) {
                setState(() {
                  if (selected != null) {
                    selectedAlgorithm = selected;
                    ref.read(treeAlgorithmProvider.notifier).state = selected;
                  }
                });
              },
            ),
            LabelledCheckbox(
              key: const Key('include_missing'),
              tooltip: '''

              **Include Missing:** If selected then the split algorithm will
              distribute observations with missing values across multiple
              datasets when calculating how to split the dataset for the
              decision tree. This then allows incomplete data to be utilised
              without discarding such observations at the cost of much more
              computation. When selected, rpart() will use maxsurrogate=5,
              usesurrogate=2. When not selected (the Rattle default), both of
              these values are set to 0.

            ''',
              label: 'Include Missing',
              provider: treeIncludeMissingProvider,
            ),
          ],
        ),

        Row(
          spacing: configWidgetSpace,
          children: [
            NumberField(
              label: 'Min Split:',
              key: const Key('minSplitField'),
              controller: _minSplitController,
              tooltip: '''

              **Min Split:** Set the minimum number of observations that must
              exist in the dataset at a node in the tree before any further
              splitting will be attempted.  The default is 20.

              ''',
              inputFormatter:
                  FilteringTextInputFormatter.digitsOnly, // Integers only
              validator: (value) => validateInteger(value, min: -1),
              min: -1,
              stateProvider: treeMinSplitProvider,
            ),
            NumberField(
              label: 'Min Bucket:',
              key: const Key('minBucketField'),
              controller: _minBucketController,
              tooltip: '''

              **Min Bucket:** Set the minimum number of observations allowed
              in any leaf node of the decision tree.  The default value is one
              third of Min Split.

              ''',
              inputFormatter: FilteringTextInputFormatter.digitsOnly,
              validator: (value) => validateInteger(value, min: 1),
              min: 1,
              stateProvider: treeMinBucketProvider,
            ),
            NumberField(
              label: 'Max Depth:',
              key: const Key('maxDepthField'),
              controller: _maxDepthController,
              tooltip: '''

              **Max Depth:** Set the maximum depth of any node of the final
              tree. The root node is considered to be depth 0 so a non-trivial
              tree starts with depth 1.  The maximum allowable depth for
              rpart() is ${maxDepthLimit.toString()} which we retain as the
              maximum depth allowable for Rattle and the default.

              ''',
              inputFormatter: FilteringTextInputFormatter.digitsOnly,
              validator: (value) =>
                  validateInteger(value, min: 0, max: maxDepthLimit),
              min: 0,
              max: maxDepthLimit,
              stateProvider: treeMaxDepthProvider,
            ),
            NumberField(
              label: 'Complexity:',
              key: const Key('complexityField'),
              controller: _complexityController,
              tooltip: '''

              **Complexity:** The complexity parameter is used to control the
              size of the decision tree and to select the optimal tree
              size.See the
              [RPart](https://www.rdocumentation.org/packages/rpart/topics/rpart.control)
              documentation for details.

              ''',
              enabled: selectedAlgorithm != AlgorithmType.conditional,
              inputFormatter: FilteringTextInputFormatter.allow(
                RegExp(r'^[0-9]*\.?[0-9]{0,4}$'),
              ),
              validator: (value) => validateDecimal(value),
              stateProvider: treeComplexityProvider,
              interval: 0.0005,
              decimalPlaces: 4,
            ),
            BuildTextField(
              label: 'Priors:',
              controller: _priorsController,
              key: const Key('priorsField'),
              textStyle: selectedAlgorithm == AlgorithmType.conditional
                  ? disabledTextStyle
                  : normalTextStyle,
              tooltip: '''

              **Priors:** Set the prior probabilities for each class to boost
              a particularly important class, by giving it a higher prior
              probability. Expects a list of numbers that sum up to 1, and of
              the same length as the number of classes in the training
              dataset: e.g.,0.5,0.5.

              ''',
              enabled: selectedAlgorithm != AlgorithmType.conditional,
              validator: (value) => _validatePriors(value),
              inputFormatter: FilteringTextInputFormatter.allow(
                RegExp(
                  r'^[0-9,.\s]*$',
                ), // Allow digits, commas, dots, whitespace.
              ),
              maxWidth: 10,
              ref: ref,
            ),
            BuildTextField(
              label: 'Loss Matrix:',
              controller: _lossMatrixController,
              key: const Key('lossMatrixField'),
              textStyle: selectedAlgorithm == AlgorithmType.conditional
                  ? disabledTextStyle
                  : normalTextStyle,
              tooltip: '''

              **Loss Matrix:** Set the weights for the outcome classes
              differently to the observed outcomes from the dataset. For
              example, for binary classification this might be 0,10,1,0 (TN,
              FP, FN, TP).

              ''',
              enabled: selectedAlgorithm != AlgorithmType.conditional,
              inputFormatter: FilteringTextInputFormatter.allow(
                RegExp(r'^[0-9,]*$'), // Allow digits and commas.
              ),
              validator: (value) => _validateLossMatrix(value),
              maxWidth: 10,
              ref: ref,
            ),
          ],
        ),
      ],
    ),
  );
}