Home > Enterprise >  conditionally use futurebuilder : Flutter
conditionally use futurebuilder : Flutter

Time:11-03

I have a page where I am fetching data from a server using a recipeId. In that page, I use the complete_model (that contains all data of the model).

But, while navigating to the page, I already have access to a slim_model(contains only id, title, image).

How to make use of the slim_model to show title and image and then populate the rest?

full_view.dart:

class FullView extends StatefulWidget {
  final String id;

  const FullView({Key? key, required this.id}) : super(key: key);

  @override
  _FullViewState createState() => _FullViewState();
}

class _FullViewState extends State<FullView> {
  late Future<FullDataModel> future;

  @override
  void initState() {
    future = Repository().getModel(widget.id);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: FutureBuilder<FullDataModel>(
        future: future,
        builder: (context, snapshot) {
          switch (snapshot.connectionState) {
            case ConnectionState.waiting:
              return const Center(
                child: CircularProgressIndicator(
                  valueColor:
                      AlwaysStoppedAnimation<Color>(ColorConstants.accent1),
                ),
              );
            default:
              if (snapshot.hasError || snapshot.data == null) {
                return const Center(
                  child: Text(
                    'Something went wrong, we are working on fixing it!',
                  ),
                );
              } else {
                final data = snapshot.data!;
                return _body(data, context);
              }
          }
        },
      ),
    );
  }
}

Navigating to full_view.dart,

 Navigator.push(
              context,
              MaterialPageRoute(
                  builder: (context) {
                    return FullView(
                      id: slimData.id,
                    );
                  },
                  fullscreenDialog: true));

Here, I already have id, title & image data in slimData, I want to show that while rest of data loads in full_view.dart

The problem is that, I have to use deep_linking or sometimes I don't have slimData => I only have the id.

So, when I have slimData, I want to use that to show title and image while rest of data loads using id.

If I don't have slimData, I just want to load everything using id.

CodePudding user response:

So, when I have slimData, I want to use that to show title and image while rest of data loads using id.

So... just do it? Where you currently have a CircularProgressIndicator, insert a conditional and if you have SlimData, show that instead of the progress indicator.

  • Related