【问题标题】:want to make shared pref work without button in flutter想要在没有按钮的情况下让共享的 pref 工作
【发布时间】:2021-02-22 08:53:48
【问题描述】:
 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()));
  }

}

错误是:

类型“未来”不是类型“小部件”的子类型

【问题讨论】:

  • 只需创建另一个方法并放入您的代码,然后在build 方法中调用它。
  • 感谢您的回复,虽然它有效,但还有一个错误,出现了几分之一秒,上面写着“type 'Future' is not a subtype of type '小部件'"
  • 我已经准确地编辑了我的问题。

标签: flutter dart flutter-layout flutter-test


【解决方案1】:

感谢@Hiwa Jalal。在返回小部件之前,您需要在 build 方法中调用 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();
  },
);

【讨论】:

  • hii,我想我的问题有所不同,我已经编辑了我的问题,因为错误是由 futurebuilder 引发的。谢谢
  • 非常感谢,非常感谢我也投了赞成票,但由于我的声望少于 15 个,所以我的投票目前还不算数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多