3

Context:

I'm trying to extend and implement a custom CupertinoSlidingSegmentedControl with some alterations.

Here is a great example of using the widget:

class _ViewState extends State<View> {
  int segmentedControlGroupValue = 0;
  final Map<int, Widget> myTabs = const <int, Widget>{
    0: Text("Item 1"),
    1: Text("Item 2")
  };

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CupertinoSlidingSegmentedControl(
          groupValue: segmentedControlGroupValue,
          children: myTabs,
          onValueChanged: (i) {
            setState(() {
              segmentedControlGroupValue = i;
            });
          }),
    );
  }
}

from @AidanMarshall's answer found here

What am I trying to do?

I am customizing the myTabs into a custom itemBuilder similarly to the ListView.builder implementation. My implementation should be used as follows:

SegmentedSlider<GenderPreference>(
  values: GenderPreference.values,
  thumbColor: Colors.blue, // or use a custom theme
  onValueChanged: (value) {
    // update profile information here
  },
  sliderItemBuilderFunction: (context, item, active) {
    return Text(
      GenderPreference.asString(item),
      style: Theme.of(context).textTheme.subtitle2!.copyWith(
        color: active
            ? Colors.white
            : Colors.green,
      ),
    );
  },
  selectedValue: GenderPreference.None,
)

With this, I am using my own sliderItemBuilderFunction function defined as follows:

typedef Widget ItemValueWidgetBuilder<T>(BuildContext context, T item, bool active);

this accepts the build context, the generic item T and a (is) active convenience field

Problem:

The problem is each time I run the widget, I get the following error for each item in values:

======== Exception caught by widgets library =======================================================
The following _TypeError was thrown building SegmentedSlider<GenderPreference>(dirty, dependencies: [_LocalizationsScope-[GlobalKey#0a25e], _InheritedTheme], state: _SegmentedSliderState<GenderPreference>#40901):
type '(BuildContext, GenderPreference, bool) => Text' is not a subtype of type '(BuildContext, dynamic, bool) => Widget'

The relevant error-causing widget was: 
  SegmentedSlider<GenderPreference> file:///C:/Users/CybeX/MyAwesomeApp/awesome-app-mobile-flutter/lib/viewcontrollers/profile/ui_profile.dart:309:20
When the exception was thrown, this was the stack: 
#0      _SegmentedSliderState.build.<anonymous closure> (package:cozy_up/framework/ui/components/slider.dart:34:28)
#1      MappedListIterable.elementAt (dart:_internal/iterable.dart:412:31)
#2      ListIterator.moveNext (dart:_internal/iterable.dart:341:26)
#3      new _GrowableList._ofEfficientLengthIterable (dart:core-patch/growable_array.dart:188:27)
#4      new _GrowableList.of (dart:core-patch/growable_array.dart:150:28)
...
====================================================================================================
Reloaded 0 libraries in 1 536ms.

Question:

'(BuildContext, GenderPreference, bool) => Text' is not a subtype of type '(BuildContext, dynamic, bool) => Widget'

Firstly, the '(BuildContext, GenderPreference, bool) => Text' is my custom function, which should return a Widget as specified in the typedef.

Force Widget inside Slider's build function?

If I force this as a Widget with

Widget _widget = widget.sliderItemBuilderFunction(context, e, e == activeValue);

in my slider build function, I get exactly the same error.

Force Widget inside itemBuilder's function?

Further, if I return a Widget in my sliderItemBuilderFunction() implementation, I get the same error, but

'(BuildContext, GenderPreference, bool) => Widget' is not a subtype of type '(BuildContext, dynamic, bool) => Widget'

What am I doing wrong?


Enum Used

enum GenderPreference {
  Male,
  Female,
  Other,
  None,
}

extension GenderPreferenceExt on GenderPreference {
  static const enums = {
    GenderPreference.Male: 'Male',
    GenderPreference.Female: 'Female',
    GenderPreference.Other: 'Other',
    GenderPreference.None: 'None',
  };

  static String asString(GenderPreference genderPreference) {
    return enums[genderPreference] ?? "";
  }

  static GenderPreference parse(String _mode) {
    if (_mode == "" || _mode == null) {
      return GenderPreference.None;
    }
    return enums.entries
        .where((element) => element.value.toLowerCase() == _mode.toLowerCase())
        .first
        .key;
  }
}

Full Slider Implementation:

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

typedef Widget ItemValueWidgetBuilder<T>(
    BuildContext context, T item, bool active);

class SegmentedSlider<T> extends StatefulWidget {
  final Color backgroundColor;
  final Color thumbColor;
  final ValueChanged<T?> onValueChanged;
  final T selectedValue;
  final List<T> values;
  final ItemValueWidgetBuilder<T> sliderItemBuilderFunction;

  const SegmentedSlider(
      {Key? key,
      this.thumbColor = Colors.grey,
      this.backgroundColor = Colors.white,
      required this.onValueChanged,
      required this.sliderItemBuilderFunction,
      required this.selectedValue,
      required this.values})
      : super(key: key);

  @override
  _SegmentedSliderState<T> createState() => new _SegmentedSliderState<T>();
}

class _SegmentedSliderState<T> extends State<SegmentedSlider> {
  late T activeValue;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    activeValue = widget.selectedValue;
  }

  @override
  Widget build(BuildContext context) {
    List<MapEntry<T, Widget>> map = widget.values.map((e) {
      var _widget =
          widget.sliderItemBuilderFunction(context, e, e == activeValue);
      print(_widget);
      return MapEntry<T, Widget>(e, Container());
    }).toList();
    Map<T, Widget> children = Map.fromEntries(map);

    return CupertinoSlidingSegmentedControl<T>(
      backgroundColor: widget.backgroundColor,
      thumbColor: widget.thumbColor,
      onValueChanged: (value) {
        activeValue = value!;
        widget.onValueChanged(value);
      },
      children: children,
      groupValue: widget.selectedValue,
    );
  }
}
CybeX
  • 2,060
  • 3
  • 48
  • 115

1 Answers1

4

The essential problem is that _SegmentedSliderState does not automatically know how to parameterize the type of its parent widget, so the inherited widget property has the type SegmentedSlider<dynamic> instead of SegmentedSlider<T>.

To fix this, just declare your class like so:

class _SegmentedSliderState<T> extends State<SegmentedSlider<T>> {
                                                            ^^^
Michael Horn
  • 3,819
  • 9
  • 22