想要在没有按钮的情况下共享 pref 工作

want to make shared pref work without button in flutter

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

当我指向 nextPage() 函数时,我的 FutureBuilder 抛出错误。

这是我的 nextPage() 函数,它指向 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()));
  }

}

错误是:

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

感谢@Hiwa Jalal。在返回小部件之前,您需要在构建方法中调用 goToPage() 方法。


  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(),
      ),
    );
  }

编辑:

好的,你需要保持简单。


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();
  },
);