Flutter第三方插件objectbox的使用

Flutter基础

demo地址
参考地址


文章目录

  • Flutter基础
  • 前言
  • 一、demo效果图
  • 二、objectbox是什么?
  • 三、objectbox的使用
    • 1.在pubspec.yaml文件中添加
    • 2.执行flutter pub get命令
    • 3.创建数据库模型
    • 4.执行flutter pub run build_runner build 命令
    • 5.如果报错则执行flutter pub run build_runner build --delete-conflicting-outputs 命令
  • 三、demo代码
    • 1.order_data_table.dart文件
    • 2.home_page.dart文件
  • 总结


前言

这篇文章主要分享flutter第三方插件objectbox的简单使用。


一、demo效果图

Flutter第三方插件objectbox的使用_第1张图片

二、objectbox是什么?

ObjectBox Flutter database is a great option for storing Dart objects in your cross-platform apps. Designed for high performance, the ObjectBox Flutter database is ideal or mobile and IoT devices. ObjectBox uses minimal CPU, memory and battery, making your app not only effective, but also sustainable. By storing data locally on device, ObjectBox helps you cut your cloud costs down and make an app that doesn't depend connection. Get started with our intuitive native Dart API in minutes, without the hassle of SQL. Plus: We built a data synchronization solution that allows you to keep data in sync across devices and servers, both online and offline.

翻译:
ObjectBox Flutter数据库是在你的跨平台应用程序中存储Dart对象的一个很好的选择。ObjectBox Flutter数据库专为高性能而设计,是移动和物联网设备的理想选择。ObjectBox使用最少的CPU、内存和电池,使您的应用程序不仅有效,而且可持续。通过在设备上本地存储数据,ObjectBox可以帮助你降低云计算成本,并制作一个不依赖连接的应用程序。在几分钟内开始使用我们直观的本机Dart API,没有SQL的麻烦。另外:我们构建了一个数据同步解决方案,允许您在设备和服务器之间保持数据同步,包括在线和离线。

三、objectbox的使用

1.在pubspec.yaml文件中添加

objectbox: 1.6.2
objectbox_flutter_libs: 1.6.2

2.执行flutter pub get命令

如图可以看到已经把objectbox_flutter_lbs库拉下来了

3.创建数据库模型

import 'package:objectbox/objectbox.dart';

()
class ShopOrder {
  int id;
  int price;
  final customer = ToOne<Customer>();

  ShopOrder({this.id = 0, required this.price});
}

()
class Customer {
  int id;
  String name;
  ()
  final orders = ToMany<ShopOrder>();
  Customer({this.id = 0, required this.name});
}

4.执行flutter pub run build_runner build 命令

这时会自动生成objectbox.g.dart和objectbox-model.json文件

5.如果报错则执行flutter pub run build_runner build --delete-conflicting-outputs 命令

三、demo代码

1.order_data_table.dart文件

import 'package:flutter/material.dart';
import 'package:flutter_objectbox/entities.dart';

import '../objectbox.g.dart';

class OrderDataTable extends StatefulWidget {
  final List<ShopOrder> orders;
  final void Function(int columnIndex, bool ascending) onSort;
  final Store store;

  const OrderDataTable({
    Key? key,
    required this.orders,
    required this.onSort,
    required this.store,
  }) : super(key: key);

  
  _OrderDataTableState createState() => _OrderDataTableState();
}

class _OrderDataTableState extends State<OrderDataTable> {
  bool _sortAscending = true;
  int _sortColumnIndex = 0;

  
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      child: SingleChildScrollView(
        child: DataTable(
          sortColumnIndex: _sortColumnIndex,
          sortAscending: _sortAscending,
          columns: [
            DataColumn(
              label: Text('Number'),
              onSort: _onDataColumnSort,
            ),
            DataColumn(
              label: Text('Customer'),
            ),
            DataColumn(
              label: Text('Price'),
              numeric: true,
              onSort: _onDataColumnSort,
            ),
            DataColumn(
              label: Container(),
            ),
          ],
          rows: widget.orders.map((order) {
            return DataRow(
              cells: [
                DataCell(
                  Text(order.id.toString()),
                ),
                DataCell(
                  Text(order.customer.target?.name ?? 'NONE'),
                  onTap: () {
                    showModalBottomSheet(
                      context: context,
                      builder: (context) {
                        return Material(
                          child: ListView(
                            children: order.customer.target!.orders
                                .map(
                                  (_) => ListTile(
                                    title: Text(
                                      '${_.id}    ${_.customer.target?.name}    \$${_.price}',
                                    ),
                                  ),
                                )
                                .toList(),
                          ),
                        );
                      },
                    );
                  },
                ),
                DataCell(
                  Text(
                    '\$${order.price}',
                  ),
                ),
                DataCell(
                  Icon(Icons.delete),
                  onTap: () {
                    widget.store.box<ShopOrder>().remove(order.id);
                  },
                ),
              ],
            );
          }).toList(),
        ),
      ),
    );
  }

  void _onDataColumnSort(int columnIndex, bool ascending) {
    setState(() {
      _sortColumnIndex = columnIndex;
      _sortAscending = ascending;
    });
    widget.onSort(columnIndex, ascending);
  }
}

2.home_page.dart文件

import 'package:faker/faker.dart';
import 'package:flutter/material.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';

import '../objectbox.g.dart';
import 'entities.dart';
import 'order_data_table.dart';

class HomePage extends StatefulWidget {
  
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final faker = Faker();

  late Store _store;
  bool hasBeenInitialized = false;

  late Customer _customer;
  late Stream<List<ShopOrder>> _stream;

  
  void initState() {
    super.initState();
    setNewCustomer();
    getApplicationDocumentsDirectory().then((dir) {
      print('打印一下数据库地址==${dir.path}');
      _store = Store(
          // This method is from the generated file
          getObjectBoxModel(),
          directory: join(dir.path, 'objectbox1'));

      setState(() {
        _stream = _store
            .box<ShopOrder>()
            .query()
            .watch(triggerImmediately: true)
            .map((query) => query.find());

        hasBeenInitialized = true;
      });
    });
    setNewCustomer();
  }

  
  void dispose() {
    _store.close();
    super.dispose();
  }

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Orders App'),
        actions: [
          IconButton(
            icon: Icon(Icons.person_add_alt),
            onPressed: setNewCustomer,
          ),
          IconButton(
            icon: Icon(Icons.attach_money),
            onPressed: addFakeOrderForCurrentCustomer,
          ),
        ],
      ),
      body: !hasBeenInitialized
          ? Center(
              child: CircularProgressIndicator(),
            )
          : StreamBuilder<List<ShopOrder>>(
              stream: _stream,
              builder: (context, snapshot) {
                if (!snapshot.hasData) {
                  return Center(
                    child: CircularProgressIndicator(),
                  );
                } else {
                  return OrderDataTable(
                    orders: snapshot.data!,
                    onSort: (columnIndex, ascending) {
                      final newQueryBuilder = _store.box<ShopOrder>().query();
                      final sortField = columnIndex == 0 ? ShopOrder_.id : ShopOrder_.price;
                      newQueryBuilder.order(sortField, flags: ascending ? 0 : Order.descending);

                      setState(() {
                        _stream = newQueryBuilder
                            .watch(triggerImmediately: true)
                            .map((query) => query.find());
                      });
                    },
                    store: _store,
                  );
                }
              },
            ),
    );
  }

  void setNewCustomer() {
    _customer = Customer(name: faker.person.name());
  }

  void addFakeOrderForCurrentCustomer() {
    final order = ShopOrder(
      price: faker.randomGenerator.integer(500, min: 10),
    );
    order.customer.target = _customer;
    _store.box<ShopOrder>().put(order);
  }
}


总结

以上就是今天要讲的内容,本文简单介绍了objectbox的使用。希望文章对你有所帮助,后续继续完善。

你可能感兴趣的:(flutter,flutter)