Rahul Kumar Jha
Rahul Kumar Jha

Reputation: 69

Flutter if else condition in child

I am working on a flutter quiz application and it fetches question and images from JSON file When the app is running in question with no images I am getting a loading symbol & I need to remove that loading symbol in question with no images using if but I am running into errors I am attaching the Psuedo Code can someone tell how can I do it ???

 Expanded(
                              child: AspectRatio(
                                aspectRatio: 16 / 11,
                                child: ClipRect(
                                  child: SizedBox(
                                    height: 50,
                                    child: PhotoView(
                                      imageProvider: AssetImage(
                                          myQuestion[i]["Image"] ?? "None"),
                                      minScale:
                                      PhotoViewComputedScale.contained *
                                          0.5,
                                      maxScale:
                                      PhotoViewComputedScale.covered * 2,
                                      initialScale: 0.6,
                                      backgroundDecoration: BoxDecoration(
                                        color: Theme.of(context).canvasColor,
                                      ),
                                    ),
                                  ),
                                ),
                              ),
                            ),


Upvotes: 0

Views: 1336

Answers (1)

user12955651
user12955651

Reputation:

I cannot comment yet. And I don't know exactly what kind of error you're running in but I think is the string being provided as the image source.

You can move the logic check from the AssetImage higher in the widget tree.

Expanded(
  child: AspectRatio(
    aspectRatio: 16 / 11,
    child: ClipRect(
      child: SizedBox(
        height: 50,
        child: myQuestion[i]["Image"]!=null && myQuestion[i]["Image"].isNotEmpty() 
           ? PhotoView(
               imageProvider: AssetImage( myQuestion[i]["Image"] ), // we know it's not empty and is not null
               minScale: PhotoViewComputedScale.contained * 0.5,
               maxScale: PhotoViewComputedScale.covered * 2,
               initialScale: 0.6,
               backgroundDecoration: BoxDecoration(
                 color: Theme.of(context).canvasColor,
               ),
             )
           : Container(),
         ),
      ),
   ),
),

We use a ternary operator to check if the asset is not null and is not empty. If it has a valid value we display the image otherwise we display and empty container. This logic can be moved up the widget tree depending on what you want to display and where.

Upvotes: 1

Related Questions