skip to Main Content

While I’m making an app, my IDE raised an error that part of my code is dead.

The only problem is that, I don’t know why it’s giving me that error

I tried rewriting the code and even going to other widgets to see the code, but the issue still rises.
Here’s part of the code that’s affected.

!loading? Align(
                                alignment: Alignment.topLeft,
                                child: ElevatedButton(
                                    onPressed: () async {
                                      setState(() {
                                        loading = true;
                                      });
                                      final path = '${FirebaseAuth.instance.currentUser?.uid}/${widget.index}/${pickedfile!.name}';
                                      final ref = FirebaseStorage.instance.ref().child(path);
                                      uploadTask = ref.putData(pickedfile!.bytes!);
                                      await uploadTask!.whenComplete((){});
                                      final snapshot = uploadTask!.snapshot;
                                      final urlDownload = await snapshot.ref.getDownloadURL();
                                      await FirebaseFirestore.instance.collection("Users").doc("${FirebaseAuth.instance.currentUser?.uid}").collection("Videos").doc("Video ${widget.index}").set({
                                        pickedfile!.name : urlDownload
                                      });
                                    },
                                    child: Text("Activate")
                                )
                              ):/*This part is the dead code*/Align(
                                alignment: Alignment.topLeft,
                                child: CircularProgressIndicator(),
                              )

and the code for the stateful widget

class VideoGptDialog extends StatefulWidget {
  final int index;
  const VideoGptDialog({required this.index, Key? key}) : super(key: key);

  @override
  State<VideoGptDialog> createState() => _VideoGptDialogState();
}

class _VideoGptDialogState extends State<VideoGptDialog> {
  TextEditingController gptController = TextEditingController();
  PlatformFile? pickedfile;
  UploadTask? uploadTask;
  late VideoPlayerController _controller;
  @override
  Widget build(BuildContext context) {
    bool loading = false;
    return Dialog(
      backgroundColor: Colors.transparent,
      child: Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.all(Radius.circular(20))
        ),
        child: SizedBox(
          width: 1000,
          height: 700,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Align(
                alignment: Alignment.topRight,
                child: IconButton(
                  icon: Icon(Icons.close),
                  onPressed: () {Navigator.pop(context);},
                ),
              ),
              Align(
                alignment: Alignment.center,
                child: Column(
                  children: [
                    Text(
                        "Short Clip a video",
                      style: TextStyle(
                        fontFamily: 'poppins',
                        fontSize: 24
                      ),
                    ),
                    SizedBox(height: 20,),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        InkWell(
                          onTap: () async{
                            final result = await FilePicker.platform.pickFiles(type: FileType.video);
                            if(result != null){
                              setState(() {
                                pickedfile = result.files.first;
                              });
                            }
                          },
                          child: Container(
                            width: 300,
                            height: 300,
                            decoration: BoxDecoration(
                                boxShadow: [BoxShadow()],
                                borderRadius: BorderRadius.all(Radius.circular(10)),
                                border: Border.all(color: Colors.blue),
                                color: Colors.white
                            ),
                            child: pickedfile == null? Icon(Icons.add, color: Colors.blue, size: 128,):Center(child: Text(pickedfile!.name.toString())),
                          ),
                        ),
                        SizedBox(width: 10,),
                        SizedBox(
                          width: 300,
                          height: 300,
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              Align(
                                alignment: Alignment.topLeft,
                                child: Text("What would you like to extract"),
                              ),
                              SizedBox(height: 10,),
                              Align(
                                alignment: Alignment.topLeft,
                                child: TextField(
                                  controller: gptController,
                                  decoration: InputDecoration(
                                    border: OutlineInputBorder(
                                      borderSide: BorderSide(
                                        width: 3, color: Colors.black
                                      )
                                    )
                                  ),
                                ),
                              ),
                              !loading? Align(
                                alignment: Alignment.topLeft,
                                child: ElevatedButton(
                                    onPressed: () async {
                                      setState(() {
                                        loading = true;
                                      });
                                      final path = '${FirebaseAuth.instance.currentUser?.uid}/${widget.index}/${pickedfile!.name}';
                                      final ref = FirebaseStorage.instance.ref().child(path);
                                      uploadTask = ref.putData(pickedfile!.bytes!);
                                      await uploadTask!.whenComplete((){});
                                      final snapshot = uploadTask!.snapshot;
                                      final urlDownload = await snapshot.ref.getDownloadURL();
                                      await FirebaseFirestore.instance.collection("Users").doc("${FirebaseAuth.instance.currentUser?.uid}").collection("Videos").doc("Video ${widget.index}").set({
                                        pickedfile!.name : urlDownload
                                      });
                                    },
                                    child: Text("Activate")
                                )
                              ):/*This part is the dead code*/Align(
                                alignment: Alignment.topLeft,
                                child: CircularProgressIndicator(),
                              )
                            ],
                          ),
                        )
                      ],
                    ),
                  ],
                ),
              ),
              const SizedBox()
            ],
          ),
        ),
      ),
    );
  }
}

3

Answers


  1. You declared loading inside the build method, which make the value of loading will always be false every time the widget rebuilds.

    @override
    Widget build(BuildContext context) {
      bool loading = false; // Don't do this
      // ...
    

    This is a wrong usage of StatefulWidget. Move the declaration of loading to the State.

    class _VideoGptDialogState extends State<VideoGptDialog> {
      bool loading = false;
      // ...
    }
    
    Login or Signup to reply.
  2. because of

    bool loading = false;
    

    loading is always false. so this

    !loading? ... : ...;
    

    is always true. so second part is dead code and never will be reached. you shouldn’t declare it in build method but

    class _VideoGptDialogState extends State<VideoGptDialog> {
    
    var loading = false;
    ...
    
    Login or Signup to reply.
  3. The issue of "dead code" generally refers to code that is written but never executed or reached during the program’s execution. In your case, the IDE is likely indicating that a specific part of your code will not be executed under any circumstances.

    Looking at your code, the suspected "dead code" is within this section:

    !loading? Align(
      alignment: Alignment.topLeft,
      child: ElevatedButton(
        // Button code...
      )
    ) : /*This part is the dead code*/Align(
      alignment: Alignment.topLeft,
      child: CircularProgressIndicator(),
    )
    

    Here’s why this might be considered dead code:

    1. State Management: The variable loading is initialized as false and
      does not seem to be updated anywhere before this conditional
      statement. This means the condition !loading will always be true,
      and the false branch of the ternary operator (the
      CircularProgressIndicator part) will never be executed.
    2. Variable Scope: Since loading is a local variable within the build
      method and is not updated anywhere in the provided code, its value
      remains constant during the lifecycle of the build method.

    To fix this, you need to ensure that the value of loading can change based on some condition, triggering a rebuild of the widget to show the CircularProgressIndicator. Here’s a suggestion:

    • You can update the loading variable within the onPressed method of
      your ElevatedButton. When the upload process starts, set loading to
      true, and once the process is completed or fails, set it back to
      false.

    Here’s a revised example:

    onPressed: () async {
      setState(() {
        loading = true;
      });
    
      try {
        // Your file upload logic here
      } finally {
        setState(() {
          loading = false;
        });
      }
    },
    

    This way, when the button is pressed, loading becomes true, causing the widget to rebuild and display the CircularProgressIndicator. Once the upload process is complete (or fails), loading is set back to false, hiding the CircularProgressIndicator and showing the button again.

    Remember to call setState to trigger a rebuild of your widget whenever you change the value of loading.

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