Flutter实战之实现一个简单的新闻阅读器
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
List<News> newsList = [
News(title: '新闻标题1', content: '新闻内容1'),
News(title: '新闻标题2', content: '新闻内容2'),
// ...更多新闻
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('新闻阅读器'),
),
body: ListView.builder(
itemCount: newsList.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(newsList[index].title),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => NewsPage(news: newsList[index])),
);
},
);
},
),
);
}
}
class NewsPage extends StatelessWidget {
final News news;
NewsPage({this.news});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(news.title),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Text(news.content),
),
);
}
}
class News {
final String title;
final String content;
News({this.title, this.content});
}
这段代码实现了一个简单的新闻阅读器应用,包含了新闻列表和新闻详情页面。在新闻列表中,点击新闻标题会导航到新闻详情页面。这个例子教会开发者如何在Flutter中使用ListView
和ListTile
来构建列表,以及如何使用Navigator
来处理页面导航。
评论已关闭