Flutter数据检索插件retriever的使用

Flutter数据检索插件retriever的使用

特性

1. 自动错误处理

// 如果值无效,此方法将抛出错误
Retriever.getString('key', map);

// 此方法如果值无效,则返回null
Retriever.getMaybeString('key', map);

2. 实用的错误信息

RetrieverFormatError: 在解析键时发现无效格式。
     键: "name"
     预期: "Integer"
     发现: "String", 值: "myExampleName"。
     对象: "{
              --> name: myExampleName
                  ^^^^
                  age: 40
              }"

通过retriever,您可以安全地解析:

  • 字符串
  • 整数
  • 双精度浮点数
  • 日期
  • 映射

开始使用

retriever除了依赖于dart本身外,没有任何其他依赖,并且所有方法都是静态的。这使得它易于使用且性能良好。

使用示例

给定以下映射:

final map = {
  'name': 'myExampleName',
  'age': 40,
};

您可以从映射中检索字符串,就像这样:

final string = Retriever.getString('name', map);
print(string); // 'myExampleName'

如果键不存在或值不正确,将抛出错误。这些错误非常有帮助且易于理解,明确地显示了发生了什么。

// 使用getString方法在整数值上会抛出以下错误
Retriever.getString('age', map); // 'age' 是一个整数。将抛出错误

// RetrieverFormatError: 在解析键时发现无效格式。
//      键: "name"
//      预期: "Integer"
//      发现: "String", 值: "myExampleName"。
//      对象: "{
//               --> name: myExampleName
//                   ^^^^
//                   age: 40
//               }"

其他信息

如果您发现问题,请随时提交问题发起拉取请求

所有贡献都欢迎 :)

完整示例

import 'package:retriever/retriever.dart';

class User {
  final String name;
  final int age;
  final String? address;
  final String usesDart;
  final double height;
  final DateTime birthDate;

  User({
    required this.name,
    required this.age,
    required this.address,
    required this.usesDart,
    required this.height,
    required this.birthDate,
  });
}

void main() {
  // 这个映射代表从API获取的响应
  final responseFromBackend = {
    'name': 'asdf',
    'age': 21,
    'address': null,
    'uses_dart': true,
    'height': 1.78,
    'birth_date': '2023-01-01 00:00:00.000',
  };

  // 这里我们将使用retriever并从映射中显式获取类型化的值,并轻松实例化类
  User(
    name: Retriever.getString('name', responseFromBackend),
    age: Retriever.getInt('age', responseFromBackend),
    address: Retriever.getMaybeString('address', responseFromBackend),
    usesDart: Retriever.getForceString('uses_dart', responseFromBackend),
    height: Retriever.getDouble('height', responseFromBackend),
    birthDate: Retriever.getDate('birth_date', responseFromBackend),
  );

  final map = {
    'name': 'myExampleName',
    'age': 40,
  };

  // 确保给定键具有有效值
  // 我们可以使用getString, getDouble, getInt 或 getDate 方法
  final string = Retriever.getString('name', map);
  print(string); // 'myExampleName'

  // 如果我们尝试获取不存在的键,retriever 将抛出错误
  try {
    Retriever.getString('inexistentKey', map);
  } catch (e) {
    print(e); // 这将打印以下错误...
    //
    //           RetrieverFormatError: 在解析键时发现无效格式。
    //                键: "inexistentKey"
    //                预期: "String"
    //                发现: "Null", 值: "null"。
    //                对象: "{
    //                             name: myExampleName
    //                             age: 40
    //                         }"
  }

  // 如果键存在,但其值不符合方法的要求
  // 有问题的键将被高亮以帮助我们可视化正在发生的事情
  try {
    // 让我们尝试获取一个整数
    Retriever.getInt('name', map);
  } catch (e) {
    print(e); // 这将打印以下错误...
    //
    //           RetrieverFormatError: 在解析键时发现无效格式。
    //                键: "name"
    //                预期: "Integer"
    //                发现: "String", 值: "myExampleName"。
    //                对象: "{
    //                         --> name: myExampleName
    //                             ^^^^
    //                             age: 40
    //                         }"
  }

  // 有时我们不想抛出错误
  // 在这种情况下,有一个特定的方法,而不是抛出错误
  // 将返回null
  final name = Retriever.getMaybeInt('name', map);
  print(name); // null

  // 当你想将任何值转换为字符串时
  // 你可以使用简单的方法
  final age = Retriever.getForceString('age', map);
  print(age); // 40
  print(age.runtimeType); // String
}

更多关于Flutter数据检索插件retriever的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter数据检索插件retriever的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter中,retriever 插件通常用于从本地或远程数据源检索数据。虽然没有一个广泛知名的、名为 retriever 的官方 Flutter 插件,但我们可以假设你提到的是一个用于数据检索的自定义或第三方插件。为了展示如何使用类似功能进行数据检索,我们可以参考一些常见的数据检索插件,如 sqflite(用于SQLite数据库检索)或 http(用于网络数据检索)。

下面,我将分别提供使用 sqflitehttp 插件进行数据检索的代码示例。

使用 sqflite 进行本地数据检索

首先,确保你已经在 pubspec.yaml 文件中添加了 sqflite 依赖:

dependencies:
  flutter:
    sdk: flutter
  sqflite: ^2.0.0+4  # 请检查最新版本号

然后,你可以使用以下代码在Flutter应用中创建一个SQLite数据库并执行数据检索:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('SQLite Data Retrieval'),
        ),
        body: Center(
          child: FutureBuilder<List<Map<String, dynamic>>>(
            future: _retrieveData(),
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.done) {
                if (snapshot.hasError) {
                  return Text('Error: ${snapshot.error}');
                } else {
                  final data = snapshot.data ?? [];
                  return ListView.builder(
                    itemCount: data.length,
                    itemBuilder: (context, index) {
                      return ListTile(
                        title: Text('${data[index]['name']}'),
                        subtitle: Text('${data[index]['age']}'),
                      );
                    },
                  );
                }
              } else {
                return CircularProgressIndicator();
              }
            },
          ),
        ),
      ),
    );
  }
}

Future<Database> _initDatabase() async {
  final databasePath = await getDatabasesPath();
  return openDatabase(
    join(databasePath, 'demo.db'),
    onCreate: (db, version) {
      return db.execute(
        'CREATE TABLE users ('
        'id INTEGER PRIMARY KEY,'
        'name TEXT,'
        'age INTEGER)',
      );
    },
    version: 1,
  );
}

Future<void> _insertData(Database db) async {
  db.insert(
    'users',
    {'name': 'Alice', 'age': 30},
    conflictAlgorithm: ConflictAlgorithm.replace,
  );
  db.insert(
    'users',
    {'name': 'Bob', 'age': 25},
    conflictAlgorithm: ConflictAlgorithm.replace,
  );
}

Future<List<Map<String, dynamic>>> _retrieveData() async {
  final db = await _initDatabase();
  // Optionally, insert data first if needed
  // await _insertData(db);

  final List<Map<String, dynamic>> maps = await db.query('users');
  return maps;
}

使用 http 进行网络数据检索

同样,确保你已经在 pubspec.yaml 文件中添加了 http 依赖:

dependencies:
  flutter:
    sdk: flutter
  http: ^0.13.3  # 请检查最新版本号

然后,你可以使用以下代码在Flutter应用中从网络API检索数据:

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Network Data Retrieval'),
        ),
        body: Center(
          child: FutureBuilder<List<dynamic>>(
            future: _fetchData(),
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.done) {
                if (snapshot.hasError) {
                  return Text('Error: ${snapshot.error}');
                } else {
                  final data = snapshot.data ?? [];
                  return ListView.builder(
                    itemCount: data.length,
                    itemBuilder: (context, index) {
                      return ListTile(
                        title: Text('${data[index]['name']}'),
                        subtitle: Text('${data[index]['age']}'),
                      );
                    },
                  );
                }
              } else {
                return CircularProgressIndicator();
              }
            },
          ),
        ),
      ),
    );
  }
}

Future<List<dynamic>> _fetchData() async {
  final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/users'));

  if (response.statusCode == 200) {
    // If the server did return a 200 OK response, then parse the JSON.
    List<dynamic> body = jsonDecode(response.body);
    return body;
  } else {
    // If the server did not return a 200 OK response, then throw an exception.
    throw Exception('Failed to load data');
  }
}

这两个示例分别展示了如何从本地SQLite数据库和网络API中检索数据,并在Flutter应用中显示这些数据。根据你提到的 retriever 插件的具体功能和需求,你可以调整这些代码来适应你的应用场景。

回到顶部