skip to Main Content

I’m still pretty new to Flutter. I’ve never used the Visibility class. I messed around with it in my code, but I can’t seem to get it to work to hide the ‘congratulations’ until the checkbox is pressed and make the slider disappear when the exact checkbox is pressed. I’ve included a video of what I need to accomplish. Please help!

import 'package:flutter/material.dart';


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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  static const String _title = 'Flutter Code Sample';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: _title,
      home: Scaffold(
        appBar: AppBar(title: const Text(_title)),
        body: const MyStatefulWidget(),
      ),
    );
  }
}

class LabeledCheckbox extends StatelessWidget {
  const LabeledCheckbox({
    super.key,
    required this.label,
    required this.padding,
    required this.value,
    required this.onChanged,
  });

  final String label;
  final EdgeInsets padding;
  final bool value;
  final ValueChanged<bool> onChanged;

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: () {
        onChanged(!value);
      },
      child: Padding(
        padding: padding,
        child: Row(
          children: <Widget>[
            Checkbox(
              value: value,
              onChanged: (bool? newValue) {
                onChanged(newValue!);
              },
            ),
            Expanded(child: Text(label)),
          ],
        ),
      ),
    );
  }
}

class MyStatefulWidget extends StatefulWidget {
  const MyStatefulWidget({super.key});

  @override
  State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}


class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  bool _isSelected = false;
   double _currentSliderValue = 0;
   bool _isVisible = true;



  @override
  Widget build(BuildContext context) {  
    return Form(
      key: _formKey,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          TextFormField(
            decoration: const InputDecoration(
              hintText: 'First Name',
            ),
            validator: (String? value) {
              if (value == null || value.isEmpty) {
                return 'Please Enter First Name';
              }
              return null;
            },
          ),
           TextFormField(
            decoration: const InputDecoration(
              hintText: 'Last Name',
            ),
            validator: (String? value) {
              if (value == null || value.isEmpty) {
                return 'Please Enter Last Name';
              }
              return null;
            },
          ),
          CheckboxListTile(
          title: const Text("I am graduating this semester"),
          value: _isSelected,  
          onChanged: (value) {  
              setState(() {  
              _isSelected = value!; 
              _isVisible = !_isVisible;
              
                    });  
                  }, 
          ),

          Visibility(
              child:  Text("Congratulations!!",
                style: TextStyle(fontSize: 30, color: Colors.green))),
          Center(
          child: Text("How many classes are you planning to take this semester")  
      ),  
          Slider(
          label: _currentSliderValue.round().toString(),
          value: _currentSliderValue,
          max: 8,
          divisions: 8,
          onChanged: (value) {
          setState(() {
            _currentSliderValue = value;
          });
        },
         
      ),
          Padding(
            padding: const EdgeInsets.symmetric(vertical: 16.0),
            child: ElevatedButton(
              onPressed: () {
                
                // Validate will return true if the form is valid, or false if
                // the form is invalid.
                if (_formKey.currentState!.validate()) {
                   ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(content: Text('Thank you for submitting the survey!')),
                  );
                  // Process data.
                }
              },
              child: const Text('Submit'),
            ),
          ),
        ],
      ),
  
      
    ); 
  }
}

Link to Video example

2

Answers


  1. Just Refactor to this, and avoid Visibility Widget in this case

    if(_isSelected)
      Text("Congratulations!!",
                    style: TextStyle(fontSize: 30, color: Colors.green))),
              Center(
              child: Text("How many classes are you planning to take this semester") else
              Slider(
              label: _currentSliderValue.round().toString(),
              value: _currentSliderValue,
              max: 8,
              divisions: 8,
              onChanged: (value) {
              setState(() {
                _currentSliderValue = value;
              });
            },
          ),
    

    You wouldnt need to use _isVisible variable, since your condition is based upon _isSelected value
    And Visibility is used more in the case you want to show the widget or not, but in your case, you either one to show Text Widget or Slider widget, so if..else works better and suits the requirements

    Login or Signup to reply.
  2. You can use _isVisible boolean variable to get the result:

    class MyStatefulWidget extends StatefulWidget {
      const MyStatefulWidget({Key? key}) : super(key: key);
    
      @override
      State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
    }
    
    class _MyStatefulWidgetState extends State<MyStatefulWidget> {
      final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
    
      bool _isSelected = false;
      double _currentSliderValue = 0;
      bool _isVisible = true;
    
      @override
      Widget build(BuildContext context) {
        return Form(
          key: _formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Padding(
                padding: const EdgeInsets.all(18.0),
                child: TextFormField(
                  decoration: const InputDecoration(
                    hintText: 'First Name',
                  ),
                  validator: (String? value) {
                    if (value == null || value.isEmpty) {
                      return 'Please Enter First Name';
                    }
                    return null;
                  },
                ),
              ),
              Padding(
                padding: const EdgeInsets.only(left:18.0,top: 5,right: 18),
                child: TextFormField(
                  decoration: const InputDecoration(
                    hintText: 'Last Name',
                  ),
                  validator: (String? value) {
                    if (value == null || value.isEmpty) {
                      return 'Please Enter Last Name';
                    }
                    return null;
                  },
                ),
              ),
              CheckboxListTile(
                controlAffinity: ListTileControlAffinity.leading,
                title: const Text("I am graduating this semester"),
                value: _isSelected,
                onChanged: (value) {
                  setState(() {
                    _isSelected = value!;
                    _isVisible = !_isVisible;
                  });
                },
              ),
                if (_isSelected)
                const Padding(
                  padding: EdgeInsets.only(left: 18.0),
                  child: Text(
                    "Congratulations!!",
                    style: TextStyle(fontSize: 30, color: Colors.green),
                  ),
                ),
              if (_isVisible)
                const Center(
                    child: Text(
                        "How many classes are you planning to take this semester")),
              if (_isVisible)
                Slider(
                  label: _currentSliderValue.round().toString(),
                  value: _currentSliderValue,
                  max: 8,
                  divisions: 8,
                  onChanged: (value) {
                    setState(() {
                      _currentSliderValue = value;
                    });
                  },
                ),  
           Padding(
                padding: const EdgeInsets.only(top: 26.0,left: 18),
                child: Center(
                  child: ElevatedButton(
                    onPressed: () {
                      // Validate will return true if the form is valid, or false if
                      // the form is invalid.
                      if (_formKey.currentState!.validate()) {
                         ScaffoldMessenger.of(context).showSnackBar(
                          const SnackBar(content: Text('Thank you for submitting the survey!')),
                        );
                        // Process data.
                      }
                    },
                    child: const Text('Submit'),
                  ),
                ),
              ),
            ],
          ),  
        ); 
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search