基于Flutter构建小型新闻App
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
List newsList = [];
@override
void initState() {
super.initState();
fetchNews();
}
fetchNews() async {
var url = 'https://newsapi.org/v2/top-headlines?country=us&apiKey=YOUR_API_KEY';
var response = await http.get(url);
if (response.statusCode == 200) {
var jsonResponse = json.decode(response.body);
setState(() {
newsList = jsonResponse['articles'];
});
} else {
print('Error: ${response.statusCode}');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('News App'),
),
body: ListView.builder(
itemCount: newsList.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(newsList[index]['title']),
subtitle: Text(newsList[index]['description']),
);
},
),
);
}
}
在这个代码实例中,我们创建了一个基本的新闻应用,通过调用新闻提要API获取最新新闻。我们使用ListView.builder
来高效构建一个可滚动的新闻列表。注意,你需要替换YOUR_API_KEY
为你自己的新闻API键值。
评论已关闭