问题描述
每次页面在屏幕上可见时,是否有任何回调可用?在 ios 中有一些委托方法,例如 viewWillAppear
、viewDidAppear
、viewDidload
.
Is there any callbacks available in flutter for every time the page is visible on screen? in ios there are some delegate methods like viewWillAppear
, viewDidAppear
, viewDidload
.
我想在特定页面出现在屏幕上时调用 API 调用.
I would like to call a API call whenever the particular page is on-screen.
注意:我不是在询问应用程序的状态,如前景、背景、暂停、恢复.
Note: I am not asking the app states like foreground, backround, pause, resume.
谢谢!
推荐答案
你不需要StatefulWidget
在每次屏幕显示时调用api.
You don't need StatefulWidget
for calling the api everytime the screen is shown.
在以下示例代码中,按浮动操作按钮导航到 api 调用屏幕,使用返回箭头返回,再次按下浮动操作按钮导航到 api 页面.
In the following example code, press the floating action button to navigate to api calling screen, go back using back arrow, press the floating action button again to navigate to api page.
每次访问该页面时都会自动调用api.
Everytime you visit this page api will be called automatically.
import 'dart:async';
import 'package:flutter/material.dart';
main() => runApp(MaterialApp(home: HomePage()));
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
floatingActionButton: FloatingActionButton(
onPressed: () => Navigator.push(context, MaterialPageRoute(builder: (_) => ApiCaller())),
),
);
}
}
class ApiCaller extends StatelessWidget {
static int counter = 0;
Future<String> apiCallLogic() async {
print("Api Called ${++counter} time(s)");
await Future.delayed(Duration(seconds: 2));
return Future.value("Hello World");
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Api Call Count: $counter'),
),
body: FutureBuilder(
future: apiCallLogic(),
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) return const CircularProgressIndicator();
if (snapshot.hasData)
return Text('${snapshot.data}');
else
return const Text('Some error happened');
},
),
);
}
}
这是零样板的简单代码.
This is the simple code with zero boiler-plate.
这篇关于每当页面在屏幕上时如何重新加载页面 - 颤动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!