gpt4 book ai didi

flutter - 如何使用 statelessWidget 从 Api 获取数据

转载 作者:行者123 更新时间:2023-12-02 03:12:41 24 4
gpt4 key购买 nike

我正在尝试从 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
}
}

关于flutter - 如何使用 statelessWidget 从 Api 获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57183446/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com