Flutter应用商店数据抓取插件play_store_scraper的使用

Flutter应用商店数据抓取插件play_store_scraper的使用

play_store_scraper 是一个用于从Google Play商店抓取数据的Flutter包。

开始使用

在你的Flutter项目的 pubspec.yaml 文件中添加以下依赖:

dependencies:
  ...
  play_store_scraper: any

在你的库中添加以下导入:

import 'package:play_store_scraper/play_store_scraper.dart';

如何使用

  1. 首先创建一个对象:

    PlayStoreScraper scraper = PlayStoreScraper();
    ScraperResult? _result;  
    bool _isError = true;
    String _errorMsg = "", _error = "";
    
  2. 然后将应用程序ID传递给 app 方法以获取包含所有所需数据的Future映射,例如:

    var data = await scraper.app(appID: "com.snapchat.android"); 
    
  3. 访问数据如下:

    _isError = data['isError'];
    if (_isError) {
      _errorMsg = data['message'];
      _error = data['error'];
    } else {
      _result = data['data'];
      print(_result!.title);
    }
    

完整的示例代码如下:

import 'package:flutter/material.dart';
import 'package:play_store_scraper/play_store_scraper.dart';
import 'package:url_launcher/url_launcher.dart';

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Example App',
      theme: ThemeData(
        primaryColor: Colors.black,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: HomePage(),
    );
  }
}

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

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  PlayStoreScraper scraper = PlayStoreScraper();
  ScraperResult? _result;
  bool _isError = true, _isLoading = true;
  String _errorMsg = "", _error = "";

  final TextStyle _headingStyle = TextStyle(
        fontWeight: FontWeight.bold,
        fontSize: 20,
      ),
      _valueStyle = TextStyle(
        fontSize: 18,
      );

  Widget _viewWidget({
    required String title,
    required String value,
  }) =>
      Row(
        children: [
          Text(
            title,
            style: _headingStyle,
          ),
          SizedBox(
            width: 10,
          ),
          Expanded(
            child: Text(
              value,
              textAlign: TextAlign.center,
              style: _valueStyle,
            ),
          ),
        ],
      );

  @override
  void initState() {
    super.initState();
    getInfo();
  }

  getInfo() async {
    _isLoading = true;
    var data = await scraper.app(appID: "com.snapchat.android");
    _isError = data['isError'];
    if (_isError) {
      _errorMsg = data['message'];
      _error = data['error'];
    } else {
      _result = data['data'];
    }
    _isLoading = false;
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text('App Info'),
      ),
      body: _isLoading
          ? Center(
              child: CircularProgressIndicator(),
            )
          : _isError
              ? Center(
                  child: Column(
                    children: [
                      Text(_error),
                      Text(_errorMsg),
                    ],
                  ),
                )
              : ListView(
                  padding: EdgeInsets.all(10),
                  children: [
                    if (_result != null) ...[
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceAround,
                        children: [
                          ClipOval(
                            child: Image.network(
                              _result!.icon,
                              height: 100,
                            ),
                          ),
                          SizedBox(
                            width: 20,
                          ),
                          Expanded(
                              child: Column(
                            children: [
                              Text(
                                _result!.title,
                                textAlign: TextAlign.center,
                                style: _headingStyle,
                              ),
                              SizedBox(
                                height: 10,
                              ),
                              Text(
                                "(${_result!.appID})",
                                textAlign: TextAlign.center,
                                style: _valueStyle.copyWith(fontSize: 16),
                              ),
                            ],
                          )),
                        ],
                      ),
                      SizedBox(
                        height: 20,
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: [
                          Container(
                              decoration: BoxDecoration(
                                border: Border.all(),
                              ),
                              height: 40,
                              padding: EdgeInsets.symmetric(horizontal: 5),
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Text(
                                    "installs".toUpperCase(),
                                    style:
                                        TextStyle(fontWeight: FontWeight.bold),
                                  ),
                                  SizedBox(
                                    height: 4,
                                  ),
                                  Text(_result!.installs),
                                ],
                              )),
                          Container(
                              decoration: BoxDecoration(
                                border: Border.all(),
                              ),
                              height: 40,
                              padding: EdgeInsets.symmetric(horizontal: 5),
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Text(
                                    "version".toUpperCase(),
                                    style:
                                        TextStyle(fontWeight: FontWeight.bold),
                                  ),
                                  SizedBox(
                                    height: 4,
                                  ),
                                  Text(_result!.version),
                                ],
                              )),
                          Container(
                              decoration: BoxDecoration(
                                border: Border.all(),
                              ),
                              height: 40,
                              width: 68,
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Text(
                                    "rating".toUpperCase(),
                                    style:
                                        TextStyle(fontWeight: FontWeight.bold),
                                  ),
                                  SizedBox(
                                    height: 4,
                                  ),
                                  Text(_result!.ratingsScoreText),
                                ],
                              )),
                          Container(
                              decoration: BoxDecoration(
                                border: Border.all(),
                              ),
                              height: 40,
                              width: 68,
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  if (_result!.free) ...[
                                    Text(
                                      "FREE",
                                      style:
                                          _headingStyle.copyWith(fontSize: 14),
                                    )
                                  ] else ...[
                                    Text(
                                      "price".toUpperCase(),
                                      style: TextStyle(
                                          fontWeight: FontWeight.bold),
                                    ),
                                    SizedBox(
                                      height: 4,
                                    ),
                                    Text(
                                        "${_result!.priceCurrency} ${_result!.price}"),
                                  ]
                                ],
                              )),
                        ],
                      ),
                      Divider(),
                      Text(
                        _result!.description,
                        textAlign: TextAlign.justify,
                        style: _valueStyle,
                      ),
                      Divider(),
                      _viewWidget(title: "Genre", value: _result!.genreID),
                      Divider(),
                      _viewWidget(title: "Update On", value: _result!.updated),
                      Divider(),
                      _viewWidget(
                          title: "Content for", value: _result!.contentRating),
                      Divider(),
                      _viewWidget(
                          title: "Developer", value: _result!.developer),
                      SizedBox(
                        height: 10,
                      ),
                      Wrap(
                        spacing: 10,
                        runSpacing: 5,
                        alignment: WrapAlignment.center,
                        children: [
                          ElevatedButton(
                            onPressed: () async {
                              await launch(_result!.appUrl);
                            },
                            child: Text("Open App Page"),
                          ),
                          ElevatedButton(
                            style: ButtonStyle(
                                backgroundColor:
                                    MaterialStateProperty.all(Colors.indigo)),
                            onPressed: () async {
                              await launch(_result!.developerWebsite);
                            },
                            child: Text("Open Developer Website"),
                          ),
                          TextButton(
                            onPressed: () async {
                              await launch("mailto:${_result!.developerEmail}");
                            },
                            child: Text("Mail Developer"),
                          ),
                          ElevatedButton(
                            style: ButtonStyle(
                                backgroundColor: MaterialStateProperty.all(
                                    Colors.deepOrange)),
                            onPressed: () async {
                              await launch(_result!.developerUrl);
                            },
                            child: Text("Open Developer Page"),
                          ),
                        ],
                      ),
                    ]
                  ],
                ),
    );
  }
}

成功的结果

成功结果的示例数据结构如下:

{
  'isError': false,
  'data': _data,
}

其中 _dataScraperResult 类型的数据,其定义如下:

ScraperResult({
  required this.title,
  required this.description,
  required this.updated,
  required this.size,
  required this.installs,
  required this.version,
  required this.androidVersion,
  required this.contentRating,
  required this.developer,
  required this.developerWebsite,
  required this.developerEmail,
  required this.privacyPolicy,
  required this.developerAddress,
  required this.ratingsScoreText,
  required this.ratingsScore,
  required this.ratingsCount,
  required this.price,
  required this.free,
  required this.priceCurrency,
  required this.developerID,
  required this.genre,
  required this.genreID,
  required this.icon,
  required this.appID,
  required this.appUrl,
  required this.developerUrl,
});

错误的结果

错误结果的示例数据结构如下:

{
  "isError": true,
  "error": error.toString(),
  "message": msg.toString,
}

更多关于Flutter应用商店数据抓取插件play_store_scraper的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter应用商店数据抓取插件play_store_scraper的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,关于使用Flutter的play_store_scraper插件来抓取Google Play应用商店的数据,这里提供一个简单的代码案例来展示如何使用该插件。请注意,抓取应用商店数据应遵守相关服务条款和隐私政策,确保你的行为合法且尊重数据提供者的权益。

首先,确保你已经在Flutter项目中添加了play_store_scraper依赖。你可以在pubspec.yaml文件中添加以下依赖:

dependencies:
  flutter:
    sdk: flutter
  play_store_scraper: ^latest_version  # 请替换为实际的最新版本号

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

接下来是一个简单的Flutter应用示例,展示如何使用play_store_scraper来获取一个应用的基本信息:

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

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

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String? appName;
  String? developer;
  double? rating;
  int? numReviews;
  String? description;
  List<String>? screenshots;

  @override
  void initState() {
    super.initState();
    _fetchAppData();
  }

  Future<void> _fetchAppData() async {
    try {
      // 这里替换为你想要抓取的应用包名
      String appId = 'com.example.app';
      
      var app = await GooglePlay.apps.get(appId);
      
      setState(() {
        appName = app.title;
        developer = app.developer;
        rating = app.score;
        numReviews = app.numDownloads; // 注意:这里numDownloads可能不是所有应用都提供,具体字段名可能需要根据实际情况调整
        description = app.description ?? '';
        screenshots = app.screenshots ?? [];
      });
    } catch (e) {
      print('Error fetching app data: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Play Store App Scraper'),
        ),
        body: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              if (appName != null) Text('App Name: $appName'),
              if (developer != null) Text('Developer: $developer'),
              if (rating != null) Text('Rating: $rating'),
              if (numReviews != null) Text('Number of Reviews: $numReviews'),
              if (description != null) Text('Description:\n$description'),
              if (screenshots != null && screenshots!.isNotEmpty) ...[
                SizedBox(height: 16.0),
                Text('Screenshots:'),
                GridView.builder(
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 2,
                    crossAxisSpacing: 8.0,
                    mainAxisSpacing: 8.0,
                  ),
                  itemCount: screenshots!.length,
                  itemBuilder: (context, index) {
                    return Image.network(screenshots![index]);
                  },
                ),
              ],
            ],
          ),
        ),
      ),
    );
  }
}

在这个示例中,我们使用了play_store_scraperGooglePlay.apps.get方法来获取指定应用ID的应用信息。获取到的信息包括应用名称、开发者、评分、下载量(或评论数,具体字段名需根据插件文档确认)、描述和截图等。然后,我们使用Flutter的UI组件来展示这些信息。

请注意,由于Google Play的数据可能会变化,且抓取数据可能会受到网络延迟、API限制等因素的影响,因此在实际应用中,你可能需要添加更多的错误处理和重试逻辑。

此外,由于play_store_scraper插件的API可能会随着版本的更新而变化,因此建议查阅最新的插件文档以获取最准确的信息。

回到顶部