skip to Main Content

  @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

Answers


  1. 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) {
    
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search