Flutter网络请求存储插件http_store的使用

Flutter网络请求存储插件http_store的使用

功能介绍

这个插件的功能是在通过http包获取数据后,自动将这些数据保存到SharedPreferences中。这样你就无需手动保存数据了。

使用方法

请包含一些简短且有用的示例代码供用户参考。更长的示例可以放在/example文件夹中。

import 'package:flutter/material.dart'; // 安装此包
import 'package:http_store/http_store.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: HomePageList(),
    );
  }
}

class HomePageList extends StatefulWidget {
  const HomePageList({super.key});

  [@override](/user/override)
  State<HomePageList> createState() => _HomePageListState();
}

class _HomePageListState extends State<HomePageList> {
  var bookType = 'audiobooks';

  [@override](/user/override)
  Widget build(BuildContext context) {
    final double screenWidth = MediaQuery.of(context).size.width;
    final double imageWidth = (screenWidth - 40) / 3;
    final double imageHeight = imageWidth * 1.5;
    return Scaffold(
      appBar: AppBar(),
      body: SizedBox(
        height: imageHeight + 10,
        child: HttpStore(
          apiKey:
              'https://apon06.github.io/bookify_api/sarat_chandra_chattopadhyay.json',
          saveKey: 'Hello',
          bookType: bookType,
          builder: (context, data) {
            return ListView.builder(
              scrollDirection: Axis.horizontal,
              itemCount: data.length,
              itemBuilder: (context, index) {
                dynamic book = data[index];
                return Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 5.0),
                  child: GestureDetector(
                    //! 取消注释以启用
                    // onTap: () {
                    //   Navigator.of(context).push(
                    //     MaterialPageRoute(
                    //       builder: (builder) =>
                    //           EpisodeListPage(audiobook: book),
                    //     ),
                    //   );
                    // },
                    child: Container(
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(15),
                        boxShadow: const [
                          BoxShadow(
                            color: Colors.black26,
                            spreadRadius: 1,
                            blurRadius: 5,
                          ),
                        ],
                      ),
                      child: ClipRRect(
                        borderRadius: BorderRadius.circular(8),
                        //! 使用此插件 "cached_network_image" 否则图像不会缓存,但任何文本都可以保存。
                        //! 请取消注释
                        // child: CachedNetworkImage(
                        //   imageUrl: book["bookImage"].toString(),
                        //   width: imageWidth,
                        //   height: imageHeight,
                        //   fit: BoxFit.cover,
                        //   placeholder: (context, url) =>
                        //       Container(
                        //     width: imageWidth,
                        //     height: imageHeight,
                        //     color: Colors.grey[200],
                        //     child: const Center(
                        //       child: CircularProgressIndicator(),
                        //     ),
                        //   ),
                        //   errorWidget: (context, url, error) =>
                        //       Container(
                        //     width: imageWidth,
                        //     height: imageHeight,
                        //     color: Colors.grey[200],
                        //     child: const Icon(Icons.error),
                        //   ),
                        // ),

                        //! 删除此行
                        child: Image.network(
                          book["bookImage"].toString(),
                          width: imageWidth,
                          height: imageHeight,
                        ),
                        //! 删除此行
                      ),
                    ),
                  ),
                );
              },
            );
          },
        ),
      ),
    );
  }
}

//! 取消注释以启用
// class EpisodeListPage extends StatelessWidget {
//   final dynamic audiobook;
//   const EpisodeListPage({super.key, required this.audiobook});

//   [@override](/user/override)
//   Widget build(BuildContext context) {
//     return Scaffold(
//       appBar: AppBar(
//         title: Text(
//           audiobook['bookName'],
//           style: const TextStyle(
//             fontSize: 20,
//             fontWeight: FontWeight.bold,
//           ),
//         ),
//       ),
//       body: CustomScrollView(
//         slivers: [
//           SliverToBoxAdapter(
//             child: Column(
//               children: [
//                 Padding(
//                   padding: const EdgeInsets.all(16.0),
//                   child: Container(
//                     decoration: BoxDecoration(
//                       borderRadius: BorderRadius.circular(15),
//                       boxShadow: const [
//                         BoxShadow(
//                           color: Colors.black26,
//                           spreadRadius: 1,
//                           blurRadius: 5,
//                         ),
//                       ],
//                     ),
//                     child: ClipRRect(
//                       borderRadius: BorderRadius.circular(8),
//                       child: CachedNetworkImage(
//                         imageUrl: audiobook['bookImage'],
//                         fit: BoxFit.cover,
//                       ),
//                     ),
//                   ),
//                 ),
//                 Padding(
//                   padding: const EdgeInsets.symmetric(horizontal: 16.0),
//                   child: Text(
//                     '名字: ${audiobook['bookName']}',
//                     style: const TextStyle(
//                       fontSize: 24,
//                       fontWeight: FontWeight.bold,
//                     ),
//                     textAlign: TextAlign.center,
//                   ),
//                 ),
//                 Padding(
//                   padding: const EdgeInsets.symmetric(
//                       horizontal: 16.0, vertical: 8.0),
//                   child: Text(
//                     '作者: ${audiobook['bookCreatorName']}',
//                     style: const TextStyle(
//                       fontSize: 16,
//                     ),
//                     textAlign: TextAlign.center,
//                   ),
//                 ),
//               ],
//             ),
//           ),
//           SliverList(
//             delegate: SliverChildBuilderDelegate(
//               (context, index) {
//                 final episode = audiobook['episodes'][index];
//                 return Padding(
//                   padding:
//                       const EdgeInsets.symmetric(horizontal: 16, vertical: 6),
//                   child: Card(
//                     elevation: 4,
//                     shape: RoundedRectangleBorder(
//                       borderRadius: BorderRadius.circular(8),
//                     ),
//                     child: ListTile(
//                       title: Text(
//                         episode['bookName'],
//                         style: const TextStyle(
//                           fontSize: 18,
//                           fontWeight: FontWeight.w500,
//                         ),
//                       ),
//                       trailing: const Icon(
//                         Icons.navigate_next,
//                         color: Colors.deepPurple,
//                       ),
//                       onTap: () {
//                       },
//                     ),
//                   ),
//                 );
//               },
//               childCount: audiobook['episodes'].length,
//             ),
//           ),
//         ],
//       ),
//     );
//   }
// }

更多关于Flutter网络请求存储插件http_store的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter网络请求存储插件http_store的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


http_store 是一个用于 Flutter 的网络请求存储插件,它可以帮助你轻松地管理网络请求的缓存和存储。通过 http_store,你可以将网络请求的结果缓存到本地,以便在下次请求时直接从本地获取数据,从而提高应用的性能和用户体验。

安装 http_store

首先,你需要在 pubspec.yaml 文件中添加 http_store 依赖:

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

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

基本用法

1. 初始化 HttpStore

在使用 http_store 之前,你需要先初始化它。通常,你可以在 main.dart 中进行初始化:

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 初始化 HttpStore
  await HttpStore.init();
  
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

2. 使用 HttpStore 进行网络请求

你可以使用 HttpStoreget 方法来发送网络请求,并将结果缓存到本地:

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

class MyHomePage extends StatelessWidget {
  Future<void> fetchData() async {
    final url = 'https://jsonplaceholder.typicode.com/posts';
    
    // 使用 HttpStore 进行 GET 请求
    final response = await HttpStore.get(url);
    
    if (response.statusCode == 200) {
      print('Data: ${response.body}');
    } else {
      print('Failed to load data');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('HttpStore Demo'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: fetchData,
          child: Text('Fetch Data'),
        ),
      ),
    );
  }
}

3. 设置缓存策略

你可以通过设置缓存策略来控制 HttpStore 的缓存行为。例如,你可以设置缓存的有效期:

final response = await HttpStore.get(
  url,
  cacheOptions: CacheOptions(
    maxAge: Duration(hours: 1),  // 缓存有效期为1小时
  ),
);

4. 清除缓存

如果你想手动清除缓存,可以使用 HttpStore.clearCache 方法:

await HttpStore.clearCache();

高级用法

1. 自定义缓存存储路径

你可以通过 HttpStore.init 方法自定义缓存存储路径:

await HttpStore.init(
  cacheDir: 'custom_cache_directory',
);

2. 使用 HttpStore 进行 POST 请求

HttpStore 也支持 POST 请求:

final response = await HttpStore.post(
  url,
  body: {'key': 'value'},
);

3. 处理请求头

你可以在请求中添加自定义的请求头:

final response = await HttpStore.get(
  url,
  headers: {'Authorization': 'Bearer token'},
);
回到顶部