Tab*_*san 2 state-management dart flutter
我正在尝试从 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;
}
}
Run Code Online (Sandbox Code Playgroud)
我的主页调用是
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()
Run Code Online (Sandbox Code Playgroud)
我需要调用fetchData()方法才能运行所有员工
您可以直接在您的构造函数中启动请求ChangeNotifier:
class MyNotifier with ChangeNotifer {
MyNotifier() {
// TODO: do an http request
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6267 次 |
| 最近记录: |