首页 > 解决方案 > 如何使用 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()方法才能运行所有人员

标签: flutterdartstate-management

解决方案


您可以直接在您的构造函数中启动请求ChangeNotifier

class MyNotifier with ChangeNotifer {
  MyNotifier() {
    // TODO: do an http request
  }
}

推荐阅读