Home > Software engineering >  How can I make Widget class get parameters input?
How can I make Widget class get parameters input?

Time:04-28

I am making a custom slider example and the code is :

  @override
  _MysliderState createState() => _MysliderState();
}

class _MysliderState extends State<Myslider>{
  double _value = 0;
  @override
  Widget build(BuildContext context)=>
      SliderTheme(
          data: SliderThemeData(
              activeTrackColor: Colors.white,
              thumbColor: Colors.green,
              thumbShape: RoundSliderThumbShape(enabledThumbRadius: 64)),
          child:
          Slider(
            min:-1,
            max:1,
            value:_value,
            onChanged: (value) {
              print(_value);
              setState(() {
                _value = value;
              });
            },
            activeColor: Colors.white,
            inactiveColor: Colors.white,

          ),
      );
}

And I want to use this class like following:

      appBar: AppBar(),
      backgroundColor: Colors.white,
        body:Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,

        children: [
            Myslider(thumbColor: Colors.red),
            Myslider(thumbColor: Colors.blue, min:-100),
            Myslider(thumbColor: Colors.green, max:100),
                ]

How should I change the class state to accomplish this? I am python-based and very new to dart so please excuse me for such beginner question.

CodePudding user response:

You can define params in widget like this:

class MySlider extends StatefulWidget {
  const MySlider({
    Key? key,
    // seems like default color is green in your case
    this.thumbColor = Colors.green,
    this.min = -1,
    this.max = 1,
  }) : super(key: key);

  final Color thumbColor;
  final int min;
  final int max;

  @override
  State<MySlider> createState() => _MySliderState();
}

class _MySliderState extends State<MySlider> {
  @override
  Widget build(BuildContext context) {
    // use widget's params in state
    Color thumbColor = widget.thumbColor;
    int min = widget.min;
    int max = widget.max;
    ...
  }
}
  • Related