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) {
  int treeNum = ref.watch(treeNumForestProvider);

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

  _rfSampleSizeController.text =
      ref.watch(forestSampleSizeProvider.notifier).state ?? '';

  /// Validates the sample size input for forest sampling.
  /// Returns null if valid, or an error message string if invalid.
  /// Sample size values must be positive integers not exceeding class frequencies.

  String? validateSampleSize(String? value) {
    // Allow empty/null values.

    if (value == null || value.isEmpty) {
      return null;
    }

    // Get target class frequencies and parse input values.

    List<int> targetFreq = getTargetFrequency(ref);
    List<String> inputs = value.split(',').map((s) => s.trim()).toList();

    // Check number of input values doesn't exceed number of classes.

    if (inputs.length > targetFreq.length) {
      return 'Too many values. Maximum ${targetFreq.length} allowed';
    }

    // Validate each input value.

    for (int i = 0; i < inputs.length; i++) {
      // Check if value is a positive integer.

      if (!RegExp(r'^\d+$').hasMatch(inputs[i])) {
        return 'Only positive integers allowed';
      }

      int num = int.parse(inputs[i]);
      if (num < 1) {
        return 'Values must be greater than 0';
      }

      // Ensure sample size doesn't exceed class frequency.

      if (num > targetFreq[i]) {
        return 'Sample size $num at position ${i + 1} exceeds maximum class size ${targetFreq[i]}';
      }
    }

    return null;
  }

  /// Uses [validateSampleSize] to check if [value] is valid.
  /// If valid (i.e., validateSampleSize returns null) and [value] is not null,
  /// returns 'c($value)'. Otherwise, returns the validation error.

  String formatSampleSize(String value) {
    // If value matches the pattern c(...), return it directly.
    // - This check ensures we don't re-wrap an already wrapped value.

    if (RegExp(r'^c\(.*\)$').hasMatch(value)) {
      return value;
    }

    // Validate the value.

    final validationError = validateSampleSize(value);

    // If there's a validation error, return that error.

    if (validationError != null) {
      return '';
    }

    // If the value is null or empty, there's no conversion to 'c(...)'.

    if (value.isEmpty) {
      return '';
    }

    // Otherwise, the value is valid and non-null, so convert it.

    return value;
  }

  return Column(
    spacing: configRowSpace,
    children: [
      // Space above the beginning of the configs.
      configBotGap,

      Row(
        spacing: configWidgetSpace,
        children: [
          // Space to the left of the configs.
          configLeftGap,

          // The BUILD button.
          ActivityButton(
            pageControllerProvider:
                forestPageControllerProvider, // Optional navigation

            onPressed: () async {
              String? sampleSizeError = validateSampleSize(
                _rfSampleSizeController.text,
              );

              // Collect all errors and the list may be added in future use.

              List<String> errors = [
                if (sampleSizeError != null) 'Sample Size: $sampleSizeError',
              ];

              // Check if there are any errors.

              if (errors.isNotEmpty &&
                  selectedAlgorithm == AlgorithmType.traditional) {
                // 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 random forest:\n\n${errors.join('\n')}',
                    ),
                    actions: [
                      TextButton(
                        onPressed: () {
                          Navigator.of(context).pop();
                        },
                        child: const Text('OK'),
                      ),
                    ],
                  ),
                );

                return;
              }

              // Run the R scripts.

              String mt = 'model_template';
              String mbrf = 'model_build_rforest';
              String mbcf = 'model_build_cforest';

              selectedAlgorithm == AlgorithmType.traditional
                  ? await rSource(context, ref, [mt, mbrf])
                  : await rSource(context, ref, [mt, mbcf]);

              if (selectedAlgorithm == AlgorithmType.traditional) {
                ref.read(randomForestEvaluateProvider.notifier).state = true;
                ref.read(forestSampleSizeProvider.notifier).state =
                    formatSampleSize(_rfSampleSizeController.text);
              } else if (selectedAlgorithm == AlgorithmType.conditional) {
                ref.read(conditionalForestEvaluateProvider.notifier).state =
                    true;
              }

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

              ref.read(forestEvaluateProvider.notifier).state = true;

              await ref.read(forestPageControllerProvider).animateToPage(
                    // Index of the second page.
                    1,
                    duration: const Duration(milliseconds: 300),
                    curve: Curves.easeInOut,
                  );
            },
            child: const Text('Build Random Forest'),
          ),

          Text('Target: ${getTarget(ref)}'),

          ChoiceChipTip<AlgorithmType>(
            options: AlgorithmType.values,
            getLabel: (AlgorithmType type) => type.displayName,
            selectedOption: selectedAlgorithm,
            tooltips: forestTooltips,
            onSelected: (AlgorithmType? selected) {
              setState(() {
                if (selected != null) {
                  selectedAlgorithm = selected;
                  ref.read(algorithmForestProvider.notifier).state = selected;
                }
              });
            },
          ),
        ],
      ),

      Row(
        spacing: configWidgetSpace,
        children: [
          // Space to the left of the configs.
          configLeftGap,

          NumberField(
            label: 'Trees:',
            key: const Key('treeForest'),
            controller: _treesController,
            tooltip: '''

              **Trees:** This (*ntrees*) is the number of trees to grow in the
              forest. Generally 500 (the default) is a good choice. The
              rsulting model is fairly insensitive to the number of trees.

              ''',
            inputFormatter: FilteringTextInputFormatter.allow(
              RegExp(r'^[0-9]*\.?[0-9]{0,4}$'),
            ),
            validator: (value) => validateInteger(value, min: 10),
            stateProvider: treeNumForestProvider,
            interval: 10,
          ),

          NumberField(
            label: 'Variables:',
            key: const Key('forest_variables'),
            controller: _variablesController,
            tooltip: '''

              **Variables:** This (*mtry*) is the number of variables that
              will be considered as candidates at each split when partitioning
              the dataset. For classification the default is the square root
              of the number of variables. The model is generally not very
              sensitive to this value.

              ''',
            validator: validateVector,
            inputFormatter: FilteringTextInputFormatter.allow(
              RegExp(r'[0-9,\s]'),
            ),
            stateProvider: predictorNumForestProvider,
          ),

          NumberField(
            label: 'Display Tree:',
            key: const Key('treeNoForest'),
            min: 1,
            controller: _treeNoController,
            tooltip: '''

              **Display Tree:** Set this to the tree number whose rules are to
                be displayed after building the model. You can change this
                value after the forest has been built to display the rules
                generated from a different tree without having to rebuild the
                forest.

              ''',
            max: treeNum,
            validator: validateVector,
            inputFormatter: FilteringTextInputFormatter.allow(
              RegExp(r'[0-9,\s]'),
            ),
            stateProvider: treeNoForestProvider,
            onUpDownPressed: () {
              rExecute(
                ref,
                'printRandomForest(model_randomForest, '
                '${_treeNoController.text}, '
                'max.rules = ${_maxRulesController.text})',
              );
            },
          ),

          NumberField(
            label: 'Max Rules:',
            key: const Key('maxRulesForest'),
            min: 1,
            controller: _maxRulesController,
            tooltip: '''

              **Max Rules:** Set this to the maximum number of rules to
                display in the output after building the model. You can change
                this value after the forest has been built to display more or
                fewer rules without having to rebuild the forest.

              ''',
            validator: validateVector,
            inputFormatter: FilteringTextInputFormatter.allow(
              RegExp(r'[0-9,\s]'),
            ),
            stateProvider: maxRulesForestProvider,
            onUpDownPressed: () {
              rExecute(
                ref,
                'printRandomForest(model_randomForest, '
                '${_treeNoController.text}, '
                'max.rules = ${_maxRulesController.text})',
              );
            },
          ),

          BuildTextField(
            label: 'Sample Size:',
            controller: _rfSampleSizeController,
            key: const Key('rfSampleSizeField'),
            textStyle: selectedAlgorithm == AlgorithmType.conditional
                ? disabledTextStyle
                : normalTextStyle,
            tooltip: '''

              **Sample Size:** Use this to specify either a single sample size
              (e.g. 500) or a sample size for each class (e.g., 500,500 for a
              binary model). This is the sample size for the subset of the
              training dataset chosen for each of the different tree
              builds. The sample size for each class is useful in balancing
              class predictions.

              ''',
            enabled: selectedAlgorithm != AlgorithmType.conditional,
            validator: (value) => validateSampleSize(value),
            inputFormatter: FilteringTextInputFormatter.allow(
              RegExp('[0-9,]'),
            ),
            maxWidth: 10,
            ref: ref,
          ),

          LabelledCheckbox(
            key: const Key('imputeForest'),
            tooltip: '''

            **Impute:** The random forest algorithm will ignore observations
            with missing values by default. Enable this checkbox to have
            missing values imputed as the median (numerical) or most frequent
            (categoric) value using
            [randomForest::na.roughfix](https://www.rdocumentation.org/packages/randomForest/topics/na.roughfix).

            ''',
            label: 'Impute',
            provider: imputeForestProvider,
          ),
        ],
      ),
    ],
  );
}