want to make shared pref work without button in flutter

Viewed 54
 FutureBuilder(
   future: Future.delayed(Duration(seconds: 3)),
   builder: (c, s) =>
   s.connectionState != ConnectionState.done
     ? Center(child: CircularProgressIndicator())
     :  nextPage()

When I am pointing to the nextPage() function, my FutureBuilder throws an error.

Here is my nextPage() function, where it is pointing in the FutureBuilder:

nextPage() async{

  bool visitedFlag = await getVIsitingFlag();
  setVIsitingFlag();
  if (visitedFlag == true) {
    Navigator.of(context).push(
      MaterialPageRoute(builder: (context) => HomeScreen()));
  }
  else {
    Navigator.of(context).push(
      MaterialPageRoute(builder: (context) => NewScreen()));
  }

}

The error is:

type 'Future' is not a subtype of type 'Widget'

1 Answers

Thanks to @Hiwa Jalal. You need to call your goToPage() method in your build method before returning the widget.


  Future goToPage() async {
    bool visitedFlag = await getVIsitingFlag();
    setVIsitingFlag();
    if (visitedFlag == true) {
      Navigator.of(context)
          .push(MaterialPageRoute(builder: (context) => HomeScreen()));
    } else {
      Navigator.of(context)
          .push(MaterialPageRoute(builder: (context) => NewScreen()));
    }
  }

  @override
  Widget build(BuildContext context) {
    // You will call it in here!
    goToPage();

    return MaterialApp(
      title: 'Title',
      home: Scaffold(
        body: Container(),
      ),
    );
  }

EDIT:

Ok, you need to keep it simple.


FutureBuilder(
  future: Future.delayed(Duration(seconds: 3)).then((response) {
    nextPage();    
  }),  
  builder: (context, snapshot) {
    if (snapshot.hasData) {
      return null;
    } else if (snapshot.hasError)
      return Text(snapshot.error.toString());
    return CircularProgressIndicator();
  },
);

Related