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

标签 flutter dart state-management

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

相关文章:

Flutter中的Android锁屏小部件?

list - 在 Flutter/Dart 中映射多个列表?

dart - 如何在堆栈中定位小部件,但不匹配父级的宽度/高度?

flutter - 在构建函数之外使用BuildContext

angular - 状态管理(i.ngrx/store)给 Angular 2 带来了什么?

firebase - MissingPluginException(未在 channel plugins.flutter.io/firebase_auth 上找到方法 signInWithCredential 的实现)

flutter - 如何实现 Flutter 搜索应用栏

flutter - 如何在工厂构造函数中为变量赋值而不使其静态化?

c# - ASP.NET SQL Server状态管理——获取appid

listview - Flutter:使用 ChangeNotifierProvider 管理 ListView 中多个项目的状态