Flutter新闻摘要插件inshorts_flutter的使用

Flutter新闻摘要插件inshorts_flutter的使用

概览



InShorts Flutter API

获取InShorts应用的私有API在Flutter中的访问权限

GitHub

预览图

分类

  • 所有新闻
  • 趋势
  • 头条
  • 国内
  • 商业
  • 政治
  • 体育
  • 科技
  • 初创公司
  • 娱乐
  • 怪异
  • 教育
  • 世界
  • 汽车
  • 科学
  • 旅行
  • 杂项
  • 时尚

使用

添加依赖

pubspec.yaml文件中添加依赖:

dependencies:
  ...
  inshorts_flutter: latest_version

获取新闻

import 'package:flutter/material.dart';
import 'package:inshorts_flutter/inshorts_flutter.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'InShorts News',
        debugShowCheckedModeBanner: false,
        theme: ThemeData(
          primarySwatch: Colors.deepPurple,
        ),
        home: const HomePage());
  }
}

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with SingleTickerProviderStateMixin {
  TabController? _controller;

  List categories = [NewsType.allNews, NewsType.trending, NewsType.topStories, NewsType.business];

  @override
  void initState() {
    super.initState();
    _controller = TabController(length: categories.length, vsync: this);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          centerTitle: true,
          title: const Text('InShorts News'),
          bottom: TabBar(
              controller: _controller, 
              tabs: categories.map((e) => Tab(text: InShorts.getNewsTitle(e))).toList())),
      body: TabBarView(
        controller: _controller,
        children: categories.map((e) => FutureBuilder<Data>(
            future: InShorts.getNews(newsType: e, language: Language.en),
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return ListView.builder(
                  itemCount: snapshot.data?.newsList?.length ?? 0,
                  itemBuilder: (context, index) {
                    News news = snapshot.data!.newsList![index];
                    return ListTile(
                      leading: Image.network(news.newsObj!.imageUrl!, width: 80, fit: BoxFit.fitWidth),
                      title: Text(news.newsObj!.title!),
                      subtitle: Text(
                        news.newsObj!.sourceName!,
                        style: const TextStyle(color: Colors.grey, fontWeight: FontWeight.bold, fontSize: 13),
                      ),
                    );
                  },
                );
              } else if (snapshot.hasError) {
                return const Center(child: Text('Errr'));
              }
              return const Center(child: CircularProgressIndicator());
            })).toList(),
      ),
    );
  }

  @override
  void dispose() {
    _controller?.dispose();
    super.dispose();
  }
}

数据结构

Data 类

class Data{
    List<News>? newsList;
    String? message;
}

News 类

class News{
  String? hashId;
  int? rank;
  int? version;
  String? type;
  bool? readOverride;
  bool? fixedRank;
  NewsObj? newsObj;
}

NewsObj 类

class NewsObj{
  String? oldHashId;
  String? hashId;
  String? authorName;
  String? content;
  String? sourceUrl;
  String? sourceName;
  String? title;
  bool? important;
  String? imageUrl;
  String? shortenedUrl;
  int? createdAt;
  int? score;
  List<String>? categoryNames;
  List<String>? relevancyTags;
  String? tenant;
  String? fbObjectId;
  int? fbLikeCount;
  String? countryCode;
  List<String>? targetedCity;
  String? bottomHeadline;
  String? bottomText;
  bool? darkerFonts;
  String? bottomPanelLink;
  String? bottomType;
  int? version;
  bool? dontShowAd;
  String? pollTenant;
  bool? videoOpinionEnabled;
  String? language;
  bool? showInshortsBrandName;
  bool? imageForRepresentation;
 }

更多关于Flutter新闻摘要插件inshorts_flutter的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter新闻摘要插件inshorts_flutter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


inshorts_flutter 是一个用于 Flutter 的插件,旨在帮助开发者快速集成类似于 InShorts 风格的新闻摘要功能。InShorts 是一种流行的新闻应用,它以简洁的卡片形式展示新闻摘要,用户可以快速浏览新闻内容。

以下是如何在 Flutter 项目中使用 inshorts_flutter 插件的基本步骤:

1. 添加依赖

首先,在 pubspec.yaml 文件中添加 inshorts_flutter 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  inshorts_flutter: ^1.0.0  # 请使用最新版本

然后运行 flutter pub get 来安装依赖。

2. 导入插件

在你的 Dart 文件中导入 inshorts_flutter 插件:

import 'package:inshorts_flutter/inshorts_flutter.dart';

3. 使用 InShorts 组件

inshorts_flutter 插件通常提供了一个 InShortsView 组件,你可以将其直接添加到你的页面中。以下是一个简单的示例:

class NewsPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('InShorts News'),
      ),
      body: InShortsView(
        newsItems: [
          NewsItem(
            title: 'News Title 1',
            description: 'This is a short description of the news.',
            imageUrl: 'https://example.com/image1.jpg',
          ),
          NewsItem(
            title: 'News Title 2',
            description: 'This is another short description of the news.',
            imageUrl: 'https://example.com/image2.jpg',
          ),
          // 添加更多新闻项
        ],
        onItemTap: (NewsItem item) {
          // 处理新闻项点击事件
          print('News item tapped: ${item.title}');
        },
      ),
    );
  }
}

4. 自定义样式

你可以通过传递参数来自定义 InShortsView 的样式,例如卡片的背景颜色、字体大小等。

InShortsView(
  newsItems: newsItems,
  cardBackgroundColor: Colors.white,
  titleTextStyle: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
  descriptionTextStyle: TextStyle(fontSize: 14),
  onItemTap: (item) {
    // 处理点击事件
  },
)

5. 处理新闻数据

你可以从 API 或本地数据源获取新闻数据,并将其转换为 NewsItem 对象列表,然后传递给 InShortsView

List<NewsItem> newsItems = [
  NewsItem(
    title: 'News Title 1',
    description: 'This is a short description of the news.',
    imageUrl: 'https://example.com/image1.jpg',
  ),
  NewsItem(
    title: 'News Title 2',
    description: 'This is another short description of the news.',
    imageUrl: 'https://example.com/image2.jpg',
  ),
  // 添加更多新闻项
];

6. 处理点击事件

你可以通过 onItemTap 回调来处理用户点击新闻项的事件,例如导航到新闻详情页面。

onItemTap: (NewsItem item) {
  Navigator.push(
    context,
    MaterialPageRoute(
      builder: (context) => NewsDetailPage(newsItem: item),
    ),
  );
}
回到顶部