Flutter. Sliders in message Box doesn't work with gridView

Viewed 34

I need help. I am writing a program in flutter. I made a GridView with 6 items. After pressing each one, a message box appears in which I put the Slider. I passed the parameters and the structure of the Slider using the class constructor that I created for the gridView. I made a function(_parametersItem()) in which I included a List of constructors where I put a different Slider for each gridView element. After starting the application, the Slider does not change its position. I think setState was used wrong. Maybe someone has an idea what I did wrong and can help me with it. I think I misused setState. Maybe someone has an idea why Slider is not working and can help me with this? Thanks for help.

This is my code:

import 'dart:async';
import 'dart:io';
import 'dart:ui';
import 'package:flutter/cupertino(1).dart';
import 'package:flutter/material(1).dart';
import 'cart.dart';
import 'dish_object.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      theme: ThemeData(
        brightness: Brightness.dark, primarySwatch: Colors.blueGrey,
      ),
      home: const ServiceSettings(),
    );
  }
}

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

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

class _ServiceSettingsState extends State<ServiceSettings> {
  List<ServiceSet> _parameters = <ServiceSet>[];

  final List<ServiceSet> _cartList = <ServiceSet>[];
  double _currentSliderValue = 20;
  double _currentValueCzOdP = 20;
  @override
  void initState() {
    super.initState();
    _parametersItem();
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Service settings',
            style: TextStyle(
                color: Colors.white,
                fontWeight: FontWeight.bold,
                fontSize: 24.0)),
      ),
      body: _buildGridView(),
    );
  }

  GridView _buildGridView() {
    return GridView.builder(
        padding: const EdgeInsets.all(4.0),
        gridDelegate:
        const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
        itemCount: _parameters.length,
        itemBuilder: (context, index) {
          var item = _parameters[index];
          return GestureDetector(
            child: Card(
              elevation: 4.0,
              color: Colors.white24,
              margin: const EdgeInsets.all(10),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(30),
              ),
              child: Stack(
                fit: StackFit.loose,
                alignment: Alignment.center,
                children: <Widget>[
                  Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      const Padding(padding: EdgeInsets.only(top:20)),
                      Text(
                          item.name,
                          textAlign: TextAlign.center,
                          style: const TextStyle(
                              color: Colors.white,
                              fontWeight: FontWeight.bold,
                              fontSize: 24.0)
                      ),
                      const Padding(padding: EdgeInsets.only(top:20)),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          //const Padding(padding: EdgeInsets.only(right:10)),
                          const Text(
                              'Set:   ',
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                  color: Colors.white,
                                  fontWeight: FontWeight.bold,
                                  fontSize: 20.0)
                          ),
                          Text(
                              item.currentSet,
                              textAlign: TextAlign.center,
                              style: const TextStyle(
                                  color: Colors.white,
                                  fontWeight: FontWeight.bold,
                                  fontSize: 20.0)
                          ),
                        ],
                      ),
                    ],
                  ),

                ],
              ),
            ),
            onTap: () {
              showDialog(
                  context: context,
                  builder:(context){
                    return AlertDialog(
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(30),
                      ),
                      title: Text(item.name,
                          textAlign: TextAlign.center,
                          style: const TextStyle(
                              color: Colors.white,
                              fontWeight: FontWeight.bold,
                              fontSize: 34.0)
                      ),
                      content: Text('Cur. Set.: ' + item.currentSet,
                          textAlign: TextAlign.center,
                          style: const TextStyle(
                              color: Colors.white,
                              fontWeight: FontWeight.bold,
                              fontSize: 30.0)
                      ),
                      actions: <Widget>[
                        // usually buttons at the bottom of the dialog
                        StatefulBuilder(builder: (context, setState) {
                          return item.sliderSet;
                        }),
                        FlatButton(
                          child: const Text("Set",
                              style: TextStyle(
                                  color: Colors.white,
                                  fontWeight: FontWeight.bold,
                                  fontSize: 24.0)
                          ),
                          onPressed: () {
                            Navigator.of(context).pop();
                          },
                        ),
                      ],
                    );
                  });

            },
          );
        });
  }

  void _parametersItem() {
    var list = <ServiceSet>[
      ServiceSet(
        name: 'Hysteresis',
        currentSet: '2',
        color: Colors.amber,
        sliderSet: Slider(
          value: _currentSliderValue,
          min: 0,
          max: 50,
          divisions: 85,
          label: _currentSliderValue.round()
              .toString(),
          onChanged: (double value) {
            setState(() {
              _currentSliderValue = value;
              // _currentSliderValue = value;
            });
          },
        ),
      ),
      ServiceSet(
        name: 'Pump disc. time',
        currentSet: '23',
        color: Colors.deepOrange,
        sliderSet: Slider(
          value: _currentValueCzOdP,
          min: 0,
          max: 80,
          divisions: 85,
          label: _currentValueCzOdP.round()
              .toString(),
          onChanged: (double value) {
            setState(() {
              _currentValueCzOdP = value;
              // _currentSliderValue = value;
            });
          },
        ),
      ),
      ServiceSet(
        name: 'Boiler / circuit reduction',
        currentSet: '20',
        color: Colors.brown,
        sliderSet: Slider(
          value: _currentSliderValue,
          min: 0,
          max: 70,
          divisions: 85,
          label: _currentSliderValue.round()
              .toString(),
          onChanged: (double value) {
            setState(() {
              _currentSliderValue = value;
              // _currentSliderValue = value;
            });
          },
        ),
      ),
      ServiceSet(
        name: 'Sound alarm',
        currentSet: 'off',
        color: Colors.green,
        sliderSet: Slider(
          value: _currentSliderValue,
          min: 0,
          max: 50,
          divisions: 85,
          label: _currentSliderValue.round()
              .toString(),
          onChanged: (double value) {
            setState(() {
              _currentSliderValue = value;
              // _currentSliderValue = value;
            });
          },
        ),
      ),
      ServiceSet(
        name: 'User alarm',
        currentSet: '50',
        color: Colors.purple,
        sliderSet: Slider(
          value: _currentSliderValue,
          min: 0,
          max: 50,
          divisions: 85,
          label: _currentSliderValue.round()
              .toString(),
          onChanged: (double value) {
            setState(() {
              _currentSliderValue = value;
              // _currentSliderValue = value;
            });
          },
        ),
      ),
      ServiceSet(
        name: 'Pump activ. time',
        currentSet: '35',
        color: Colors.blueGrey,
        sliderSet: Slider(
          value: _currentSliderValue,
          min: 0,
          max: 50,
          divisions: 85,
          label: _currentSliderValue.round()
              .toString(),
          onChanged: (double value) {
            setState(() {
              _currentSliderValue = value;
              // _currentSliderValue = value;
            });
          },
        ),
      ),
    ];

    //setState(() {
    _parameters = list;
    //});
  }
}

This is class with parameters:

import 'package:flutter/material.dart';

class ServiceSet {
  final String name;
  final String currentSet;
  final Color color;
  Slider sliderSet;

  ServiceSet({required this.name,required this.currentSet,required this.color, required this.sliderSet});
}

enter image description here

1 Answers

The problem is that AlertDialog doesn't save state. You have to use a StatefulBuilder. You can read more here: StatefulBuilder-class.

EDIT: Giving example as requested.

void _showDialog(){
return showDialog(
context: context,
builder: (context) {
   var yourStateChangingVariablesHere = true;
   bool test = true;
   return StatefulBuilder(
      builder: (context, setState) {
      // when you call set state here it will work!
      return AlertDialog(
         actions: <Widget>[
            Center(
               child: TextButton(
                  onPressed:(){
                     setState(()=> test = !test);
                     print(test);
                  },
                  child: Text('Press Me')
               ),
            ),
         ],
      );}
   );
});
}
Related