Manish Paul
Manish Paul

Reputation: 551

Show different widget if API fails to fetch files

I'm working on an app where I need to show a button if API fails to fetch data and show a ListView.builder() is API fetches data.

The progress so far is, if the API fetches data, ListView.builder() is displayed but if it fails to fetch the data, Button is not shown and the progress indicator keeps running.

Here's my code..

import 'package:flutter/material.dart';

import '../Services/fetch_nifty_data.dart';

class NiftyScreen extends StatefulWidget {
  @override
  _NiftyScreenState createState() => _NiftyScreenState();
}

class _NiftyScreenState extends State<NiftyScreen> {
  Map<String, dynamic>? niftyDetails = {};
  late bool? isLoading;

  @override
  void initState() {
    super.initState();
    getNiftyData();
  }

  getNiftyData() async {
    setState(() {
      isLoading = true;
    });
    this.niftyDetails = await fetchNiftyData();
    setState(() {
      isLoading = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: isLoading!
          ? LinearProgressIndicator()
          : niftyDetails!.isNotEmpty
              ? ListView.builder(
                  itemCount: niftyDetails!["filtered"]["data"].length,
                  itemBuilder: (_, index) {
                    return ListTile(
                      title: Text(
                          '${niftyDetails!["filtered"]["data"][index]["strikePrice"]}'),
                    );
                  },
                )
              : Center(
                  child: MaterialButton(
                    onPressed: getNiftyData,
                    child: Text(
                      'Nothing to show. Refetch?',
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    color: Colors.red[900],
                    textColor: Colors.white,
                  ),
                ),
    );
  }
}

Can anybody help me with this?

Upvotes: 0

Views: 42

Answers (1)

user14280337
user14280337

Reputation:

Flutter has an awesome widget called a FutureBuilder which would be perfect for your problem. I have added a basic sample below, let me know if you have any questions.


class App extends StatefulWidget {
  @override
  _AppState createState() => _AppState();
}

class _AppState extends State<App> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: FutureBuilder(
        future: fetchNiftyData(),
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          // The request is processing.
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const CircularProgressIndicator();
          } //
          // An error has occured.
          else if (snapshot.hasError) {
            return const Center(child: Text('An error occured!'));,
          } //
          // The request was successfull.
          else if (snapshot.hasData) {
            return ListView.builder(
              // Your listview that displays the data.
            );
          }

          return Container();
        },
      ),
    );
  }
}


Upvotes: 1

Related Questions