flutter - 如何使用 statelessWidget 从 Api 获取数据
问题描述
我正在尝试从 api 获取新闻数据并在主页中显示新闻标题,因为我知道它不会有任何内部更改所以我决定使用StatelessWidget以及使用PROVIDER状态管理,现在我遇到了麻烦以及如何使用 StatelessWidget 调用获取方法以便我可以显示标题
这是我的获取数据类
class NewsRequest with ChangeNotifier{
static String _url ="https://newsapi.org/v2/everything?q=bitcoin&from=2019-06-24&sortBy=publishedAt&apiKey=4d990bdd71324572bca39fe31edc3990";
static Map<String, String> _apiKey = {"apiKey" : "4d990bdd71324572bca39fe31edc3990"};
Map <String, dynamic> _data;
List _articles;
bool _isFetching = false;
Map<String, dynamic> result;
bool get isFetching => _isFetching;
Future<Map<String, dynamic>> fetchData() async{
_isFetching = true;
try{
Response response = await get(Uri.encodeFull(_url), headers: _apiKey)
.timeout(Duration(seconds: 60));
print("STATUSCODE ${response.statusCode}");
if(response.statusCode == 200){
_data = json.decode(response.body);
}
_isFetching = false;
notifyListeners();
}on SocketException catch(_){
}on TimeoutException catch(_){
}catch(e){
e.toString();
print('CATCH ${e.toString()}');
}
return null;
}
Map<String, dynamic> get getNews => _data;
Map<String , dynamic> getNewsData(){
if(_data == null){
print('data is null');
return null;
}else{
_articles = _data['articles'];
}
print("FIRST ARTICALE IS : ${_articles[0]}");
return null;
}
}
我的主页调用是
body: newsResponse.isFetching
? Center(
child: CircularProgressIndicator(),
)
: newsResponse.getNewsData()!= null ?
new ListView.builder(
itemCount: newsResponse.getNewsData().length,
itemBuilder: (BuildContext context, int index) {
return new Container(
padding: EdgeInsets.all(10),
child: Stack(
children: <Widget>[
Container(
height: 100,
width: 310,
),
child: Wrap(children: <Widget>[
Text( newsResponse.result['response'][index]['title']),
]),
),
CircleAvatar(
radius: 50,
backgroundImage: NetworkImage(
newsResponse.result['response'][index]["urlToImage"]??"",
),
),
],
),
);
},
):
Container()
我需要调用fetchData()方法才能运行所有人员
解决方案
您可以直接在您的构造函数中启动请求ChangeNotifier
:
class MyNotifier with ChangeNotifer {
MyNotifier() {
// TODO: do an http request
}
}
推荐阅读
- swift - 使用谷歌地图 ios sdk 和 swiftui 自定义标记信息窗口
- scala - 如何计算 scala/spark 中的对数损失指标?
- node.js - 使用 Node.js 和 activedirectory2 读取 Active Directory thumbnailPhoto 并将其显示为 svg
- php - 使用php ajax从下拉列表中选择后如何获取数据
- reactjs - 在 Tab 组件中使用 AntD Icon 应该有 type prop 或 component prop 错误
- wordpress - 如何从 Laravel 共享会话到 WordPress
- javascript - 如何使用用于 PWA 应用程序的 javascript 检测设备级别通知打开或关闭?
- javascript - guternbery 编辑器:javascripte 修改内容以保存到块对象
- c# - 从数据库中获取所有记录并通过网格一一打印
- java - ec2实例中的服务器返回https流量的最简单方法是什么?