My slider have value well changed , but cant move it , or cant display changes

25 Views Asked by At

  @override
  Widget build(BuildContext context) {
    double currentSliderValue = 100.0;
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Slider(
        value: currentSliderValue,
        onChanged: (double value) {
          setState(() {
            currentSliderValue = value;
          });
        },
        label: '$currentSliderValue',
      ),
      ),
    );
  }
}

I tyied to make a slider , its very similir as other example, its value could be changed, but didnt move at all

2

There are 2 best solutions below

0
5iqman On

the problem is that you initialize the value inside the build method, which is called every time the widget is rendered, as with setState.

Just change to this

double currentSliderValue = 100.0;     
@override
  Widget build(BuildContext context) {
0
Abdul Awal On

The slider holds values from 0 to 1. And your initial value is 100. Which is giving you the error.

Slider(
        value: currentSliderValue,
.....
)

Here is your working code.

import 'package:flutter/material.dart';

void main() {
  runApp(
    MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      debugShowCheckedModeBanner: false,
      home: HomePage(title: "Home Page"),
    ),
  );
}

class HomePage extends StatefulWidget {
  HomePage({super.key, required this.title});
  String title;

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  double currentSliderValue = 1;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Slider(
        value: currentSliderValue,
        onChanged: (double value) {
          setState(() {
            currentSliderValue = value;
          });
        },
        label: '$currentSliderValue',
      ),
    );
  }
}


enter image description here