📌  相关文章
📜  元素类型“GestureDetector?”不能分配给列表类型“小部件”. (1)

📅  最后修改于: 2023-12-03 14:50:02.711000             🧑  作者: Mango

Unsupported type error: "The element type 'GestureDetector?' can't be assigned to the list type 'Widget'."

This error message occurs when trying to assign a GestureDetector? object to a list of Widget. A GestureDetector? is a nullable GestureDetector widget, and it cannot be directly added to a list of Widget which doesn't support nullable types.

To understand this error better, let's break it down:

  • GestureDetector: A widget that detects gestures made by the user on the screen.
  • Widget: The basic building block for constructing user interfaces in Flutter.
  • GestureDetector?: A nullable GestureDetector widget that may contain either a GestureDetector or null.

In Flutter, Widget is the base class for all other widgets, and for most widget containers, like List<Widget>, expect non-nullable Widget types.

Solution

To resolve this error, you have a few options:

  1. Change the list type: If you only have a single GestureDetector? object to store, you can change the list type to List<GestureDetector?> instead of List<Widget>. This way, you can directly add nullable GestureDetector objects to the list without any errors.

    List<GestureDetector?> myList = [myGestureDetector];
    
  2. Convert GestureDetector? to Widget: If you need to have a List<Widget> and have a nullable GestureDetector object, you can convert the GestureDetector? widget into a Widget by using the null-aware operator (?.) with a default widget (e.g., Container) when the GestureDetector is null.

    List<Widget> myWidgetList = [myGestureDetector ?? Container()];
    

    This assigns a Container widget as a placeholder when the GestureDetector is null.

  3. Ensure non-null value: If you know that the GestureDetector? will always have non-null values and want to enforce it, change the GestureDetector? type to GestureDetector or use a non-null assertion operator (!) to remove the nullability.

    List<Widget> myWidgetList = [myGestureDetector!];
    

    The non-null assertion operator indicates that you are confident the value is never null.

Choose the appropriate solution based on your requirements and ensure that you handle null values properly if applicable.