【问题标题】:Running the function only once while the program is running程序运行时只运行一次函数
【发布时间】:2020-08-03 23:39:55
【问题描述】:

我创建了一个函数,使用 rest api 到 get 用户数据并使用他的 ID。

我在 UI 中的代码:

  SharedPreferences sharedPreferences;
  UserApiService userApiService;

  @override
  void initState() {
    super.initState();
    getUserData();
    userApiService = UserApiService();
  }

  Future<User> getUserData() async {
    sharedPreferences = await SharedPreferences.getInstance();
    int id = sharedPreferences.getInt('id');
    return userApiService.getUser(id);
  }

我在 api_service 中的代码:

  Future<User> getUser(int id) async{
    final response = await client.get('$baseUrl/user/$id');
    if(response.statusCode == 200){
      return userFromJson(response.body);
    }else return null;
  }

这是我的FutureBuilder

  @override
  Widget build(BuildContext context){
    return FutureBuilder(
      future: getUserData(),
      builder: (context, snapshot){
        if(!snapshot.hasData){
          return Scaffold(
            appBar: AppBar(
              backgroundColor: Colors.white,
              iconTheme: IconThemeData(color: Colors.black),
              title: Text('Profil', style: TextStyle(color: Colors.black, letterSpacing: 1),),
              elevation: 0.0,
              centerTitle: true,
              actions: <Widget>[
                IconButton(
                  icon: Icon(Icons.more_vert),
                  onPressed: () {
                    //
                  },
                )
              ],
              bottom: PreferredSize(child: Container(color: Colors.black, height: 0.1), preferredSize: Size.fromHeight(0.1),),
          ),
            body: Center(
              child: CircularProgressIndicator(),
            ),
          );
        }
        User user = snapshot.data;
        return Scaffold(
          backgroundColor: Colors.white,
          body: Container(
            child: Text(user.firstName),
          ),
        );
      },
    );
  }

而且我有一个问题,每次我转到完成请求的页面时,都会重新加载函数并再次从服务器检索信息。

如何让这些数据只从我的rest api下载一次,然后流畅显示,而无需再次向数据库请求该数据。

我知道我必须使用状态管理,但我不知道该怎么做。

感谢您的任何回答:)

【问题讨论】:

  • 您的意思是您希望未来在整个应用生命周期内触发一次?还是只在整个页面生命周期内触发?
  • 整个应用 /////
  • 所以下面的答案不能解决你的问题吧?
  • 仍在重新加载我的页面

标签: rest api flutter dart state


【解决方案1】:

来自https://github.com/flutter/flutter/issues/11426#issuecomment-414047398
原因:

每次发出重建时都会调用 FutureBuilder 状态的didUpdateWidget。此函数检查旧的未来对象是否与新的不同,如果是,则重新触发 FutureBuilder。

解决方案:
所以不要有:

FutureBuilder(
  future: getUserData(),
....

我们应该有:

Future _future;

@override
initState() {
  super.initState();
  _future = getUserData();
}

然后

FutureBuilder(
  future: _future,

【讨论】:

  • 谢谢,但我不知道为什么,但点击后它仍然重新加载我的页面
  • 你可以看看我的 UI 或方法是否一切正常getUserData()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多