【问题标题】:Flutter + Provider: How do I pass the value of the slider back to the provider?Flutter + Provider:如何将滑块的值传回提供者?
【发布时间】:2020-01-27 03:32:16
【问题描述】:

颤振 1.9.1 提供者 3.1.0

我目前正在构建我的第一个应用程序,我决定现在开始进行状态管理,以免在以后的构建过程中陷入困境。

我已经设置了width_restriction_provider;

class WidthRestrictionProvider extends ChangeNotifier {
  int _widthRestriction = 140;
  int get widthRestriction => _widthRestriction;

  set widthRestriction(int val) {
    _widthRestriction = val;
    notifyListeners();
  }

  changeWidthSlider(int newValue) {
    _widthRestriction = newValue;
    notifyListeners();
      }
    }

这是我的滑块小部件;

  class WidthSlider extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
       final WidthRestrictionProvider widthRestrictionProvider =
        Provider.of<WidthRestrictionProvider>(context);
        return Container(
      child: Slider(
                      min: 140.0,
                      max: 420.0,
                      onChanged: () => widthRestrictionProvider.changeWidthSlider(newValue);
                    ),

    );
  }
}

我尝试了许多不同的方法,但在此过程中一直遇到问题。

我如何成功地将新的滑块值传递回提供者?

我目前正在学习 Flutter 和 Dart,如果这个问题有点基础,我深表歉意。

【问题讨论】:

  • 这里changeWidthSlider(newValue),什么是newValue?

标签: flutter dart provider


【解决方案1】:

我通过使用statefulWidget 作为范围滑块解决了这个问题。希望它对你有用

class RangeSliderPricing extends StatefulWidget {
  const RangeSliderPricing({Key? key}) : super(key: key);

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

class _RangeSliderPricingState extends State<RangeSliderPricing> {
  RangeValues _currentRangeValues = RangeValues(20, 40);
  @override
  Widget build(BuildContext context) {
    return RangeSlider(
      values: _currentRangeValues,
      min: 0,
      max: 100,
      divisions: 5,
      labels: RangeLabels(
        _currentRangeValues.start.round().toString(),
        _currentRangeValues.end.round().toString(),
      ),
      onChanged: (RangeValues values) {
        print('on change working $values');
        setState(() {
          _currentRangeValues = values;
        });

        context.read<ProductController>().fliterByPriceRange(
            priceStart: values.start.round().toDouble(),
            priceEnd: values.end.round().toDouble());
      },
    );
  }
}

【讨论】:

    猜你喜欢
    • 2020-08-31
    • 2020-01-17
    • 2021-11-29
    • 1970-01-01
    • 2023-04-07
    • 2018-09-05
    • 2020-01-06
    • 1970-01-01
    • 2020-04-07
    相关资源
    最近更新 更多