Ankur Prakash
Ankur Prakash

Reputation: 1527

How to save and retrieve Matrix4 object of flutter's Vector_math library?

I have ValueNotifier which is initialized with Matrix4. I can transform my view. Now I want to somehow save the current value of ValueNotifier in SQLite and again on loading initialize my ValueNotifier with saved Matrix4 value. Below is code:

ValueNotifier<Matrix4> notifier = ValueNotifier(Matrix4.identity());

MatrixGestureDetector(
              onMatrixUpdate: (matrix, translationMatrix, scaleMatrix, rotationMatrix) {
                notifier.value = matrix;
              },
              child: AnimatedBuilder(animation: notifier,
                  builder: (context, child) {

                    return Transform(
                      transform: notifier.value,
                      child: Container(
                        width: width,
                        height: height,
                        color: Colors.yellow,

                      ),
                    );
                  }),
            )

Upvotes: 0

Views: 1286

Answers (1)

Richard Heap
Richard Heap

Reputation: 51722

Matrix4 has a getter storage which returns an list of 16 doubles. It also has named constructors (.fromList and .fromFloat64List) as well as the normal constructor (which takes 16 individual doubles) which will construct a Matrix4 back from its component parts.

Depending on how you'd like to store the data in SQLite you could use a combination of these. If you wanted to store all 16 doubles as columns in the database, use storage[0], storage[1], ... as your column values. You might also want to store it a character-separated string of 16 values. You could print append all 16 values with List.join(' ') and parse them back out with String.split(' ').

The most efficient way (but least human readable) is probably to store it as a BLOB of 128 bytes. Use matrix.storage.buffer.asUint8List() to convert matrix to bytes, and use Matrix4.fromBuffer(bytes.buffer, 0) to construct a matrix from a Uint8List called bytes.

Upvotes: 7

Related Questions