Home > Enterprise >  Flutter Futurebuilder's future function Gets Halfway Through And Never Finishes The Rest
Flutter Futurebuilder's future function Gets Halfway Through And Never Finishes The Rest

Time:11-06

This is the problem. The print statement in the populateProviders function is not getting run.

class _MyHomePageState extends State<MyHomePage> {
  Future<void> loadData = Future(
    () => null,
  );

  bool hostBottomNavigationBar = true;

  void toggleHostBottomNavigationBar() {
    setState(() {
      hostBottomNavigationBar = !hostBottomNavigationBar;
    });
  }

  @override
  void initState() {
    super.initState();
    loadData = populateProviders();
  }

  Future<void> populateProviders() async {
    await Provider.of<ExploreData>(context, listen: false).populate();
    await Provider.of<HostEvents>(context, listen: false).populate();
    print('This line never runs');
    return;
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
        future: loadData,
        builder: (context, snapshot) => snapshot.connectionState !=
                ConnectionState.done
            ? Scaffold(
                appBar: AppBar(title: Text('House')),
                body: Center(
                  child: CircularProgressIndicator(),
                ),
              )
            : hostBottomNavigationBar
                ? HostScaffold(widget.title, toggleHostBottomNavigationBar)
                : PartierScaffold(widget.title, toggleHostBottomNavigationBar));
  }
}

CodePudding user response:

If your statement is not set, loaddata is not set after the page is loaded first. the structure you set up is wrong mate. If you want to set up a more understandable structure, you can try the one below.

Can you delete the initstate provider function? and can you delete the function in loaddata. Also, if your populate() function doesn't have notifyListeners(), could you add it?

 @override
Widget build(BuildContext context) {
 return 
 Consumer2<ExploreData, HostEvents>(
          builder: (
            final BuildContext context,
            final ExploreData exploreData,
            final HostEvents hostEvents,
            final Widget? child,
          ) {
            return 
FutureBuilder(
    future: Future.wait([exploreData.populate(),hostEvents.populate()]),
    builder: (context, snapshot) => snapshot.connectionState !=
            ConnectionState.done

CodePudding user response:

The problem was that in the future function, there was an invalid call to an api, which caused the function to crash halfway through.

Here is the future function in question, stripped down to contain only the invalid api call and some print statements for demonstration.

Future<void> populate() async {
    print('This executes');
    var snapshot = await db
        .collection("parties")
        .where(FieldPath.documentId, whereNotIn:)
        .get();
    print('This does not execute');
  }

See here for more details

  • Related