0

i tried a lot but didnt find an Answer for my Problem or couldnt adapt it (Im not so deep in Flutter).

I have an Diary where i store the Entries as Text. This works very well! So, i wanted to add an Camera/Image Picker where you can add an Picture to the Diary Entry and save it with the Text in SQFLite. So the Camera/Image Picker works also really well. But i cant persist the Image. Everytime i reopen the Diary Entry, there is no Image. Below is my Code:

This is my Page, where i add the Diary Entries. (I sorted it out, for a better view on it

import 'dart:ffi';
import 'dart:io' as Io;
import 'dart:io';
import 'dart:typed_data';
import 'dart:ui';
import 'dart:async';
import 'dart:ui';
///import 'package:multi_image_picker/multi_image_picker.dart';
import 'package:date_format/date_format.dart';
import 'package:fischapp/Impressum.dart';
import 'package:fischapp/ReadTodoScreen.dart';
import 'package:fischapp/TimeDate.dart';
import 'package:fischapp/main.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:intl/intl.dart';
import 'package:multi_image_picker/multi_image_picker.dart';
import 'Todo.dart';
import 'DatabaseHelper.dart';
import 'ImageUploadModel.dart';
import 'dart:convert';





class DetailTodoScreen extends StatefulWidget {
  static const routeName = '/detailTodoScreen';
  final Todo todo;

  const DetailTodoScreen({Key key, this.todo}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _CreateTodoState(todo);


}


class _CreateTodoState extends State<DetailTodoScreen> {
  Todo todo;
  final descriptionTextController = TextEditingController();
  final titleTextController = TextEditingController();



  _CreateTodoState(this.todo);



  @override
  void initState() {
    super.initState();
    if (todo != null) {
      descriptionTextController.text = todo.content;
      titleTextController.text = todo.title;
    }
    }

  @override
  void dispose() {
    super.dispose();
    descriptionTextController.dispose();
    titleTextController.dispose();
  }


  Future<File> imageFile;




  File _image;
  @override
  void initState4() {
    super.initState();
  }

  void open_camera()
  async {
    var image = await ImagePicker.pickImage(source: ImageSource.camera);
    setState(() {
      _image = image;
    });

  }
  void open_gallery()
  async {
    var image = await ImagePicker.pickImage(source: ImageSource.gallery);
    setState(() {
      _image = image;
    });
  }


  File _avatarImg;

  void _getImage(BuildContext context, ImageSource source) {
    ImagePicker.pickImage(
      source: source,
      maxWidth: 400.0,
      maxHeight: 400.0,
    ).then((File image) {
      _avatarImg = image;
    });
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
     appBar: AppBar(
        title: Text('Neuer Tagebucheintrag'),
      ),
      body: ListView(
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: TextField(
              decoration: InputDecoration(
                  border: OutlineInputBorder(), labelText: "Titel"),
              maxLines: 1,
              controller: titleTextController,
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: TextField(
              decoration: InputDecoration(
                  border: OutlineInputBorder(), labelText: "Kurzbeschreibung"),
              maxLines: 5,
              controller: descriptionTextController,
            ),
          ),
          ),
          FlatButton(
            color: Colors.deepOrangeAccent,
            child: Text("Open Camera", style: TextStyle(color: Colors.white),),
            onPressed: (){

              open_camera();

            },),
          FlatButton(
            color: Colors.limeAccent,

            child:Text("Open Gallery", style: TextStyle(color: Colors.black),),
            onPressed: (){
              open_gallery();
            },
          ),
          Container(
            color: Colors.black12,
            height: 500.0,
            width: 900.0,
            child: _image == null ? Text("Hier wird das Bild dargestellt!") : Image.file(_image),
          ),
          ]),
      floatingActionButton: FloatingActionButton(
          child: Icon(Icons.check),
          onPressed: () async {
            _saveTodo(titleTextController.text, descriptionTextController.text);
            setState(() {});
          }),
    );
  }

  _saveTodo(String title, String content)
        async {
     if (todo == null) {
      DatabaseHelper.instance.insertTodo(Todo(
          title: titleTextController.text,
          content: descriptionTextController.text,

      ));
      Navigator.pop(context, "Your todo has been saved.");
    } else {
      await DatabaseHelper.instance
          .updateTodo(Todo(id: todo.id, title: title, content: content));
      Navigator.pop(context);
      setState(() {
        ReadTodoScreen();
      });
    }
  }
}

I store the Description and Title as Text with Controller and give it to the sqflite. With the FloatingActionButton, i call the saveTodo Function to store it. The Function saveTodo call then the DataBaseHelper.

Here my DatabaseHelper Class.

import 'package:flutter/cupertino.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';

import 'Todo.dart';

class DatabaseHelper {
  //Create a private constructor
  DatabaseHelper._();

  static const databaseName = 'todos_database.db';
  static final DatabaseHelper instance = DatabaseHelper._();
  static Database _database;

  Future<Database> get database async {
    if (_database == null) {
      return await initializeDatabase();
    }
    return _database;
  }

  initializeDatabase() async {
    return await openDatabase(join(await getDatabasesPath(), databaseName),
        version: 1, onCreate: (Database db, int version) async {
      await db.execute(
          "CREATE TABLE todos(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, title TEXT, content TEXT");
    });
  }

  insertTodo(Todo todo) async {
    final db = await database;
    var res = await db.insert(Todo.TABLENAME, todo.toMap(),
        conflictAlgorithm: ConflictAlgorithm.replace);
    return res;
  }

  Future<List<Todo>> retrieveTodos() async {
    final db = await database;

    final List<Map<String, dynamic>> maps = await db.query(Todo.TABLENAME);

    return List.generate(maps.length, (i) {
      return Todo(
        id: maps[i]['id'],
        title: maps[i]['title'],

      );
    });
  }

  updateTodo(Todo todo) async {
    final db = await database;

    await db.update(Todo.TABLENAME, todo.toMap(),
        where: 'id = ?',
        whereArgs: [todo.id],
        conflictAlgorithm: ConflictAlgorithm.replace);
  }

  deleteTodo(int id) async {
    var db = await database;
    db.delete(Todo.TABLENAME, where: 'id = ?', whereArgs: [id]);
  }
}

At least, the ToDo Class where the Variables are initialized:

import 'dart:typed_data';

class Todo {
  final int id;
  final String content;
  final String title;

  static const String TABLENAME = "todos";

  Todo({this.id, this.content, this.title});

  Map<String, dynamic> toMap() {
    return {'id': id, 'content': content, 'title': title};
  }
}

I tried to store it as BLOB but i didnt get it worked. Neither as BASE64 String. :( I heard about the Size increasement with BASE64 Strings but that doesnt matter.

I hope, thats all you need. Thanks so much!!

L.Ash
  • 3
  • 1

1 Answers1

0

I think you should use Shared Preferences or Hive packages for saving image or other big values than String. Sqflite is not more comfortable to do that.

Examples of saving the image to local storage:

  1. First Video
  2. Second Video

And if these solutions don't work for you, You can check another StackOverflow question where was answered; how to save the image to local storage with Sqflite. here

theiskaa
  • 1,202
  • 5
  • 25
  • Thanks for your Answer but i try to solve it with sqflite. It would take very long to build it new with shared preference or do you have an (working) example? – L.Ash Feb 06 '21 at 13:12
  • You're welcome! did you asked an example of shared preferences? – theiskaa Feb 06 '21 at 13:15
  • Here, I have pasted 2 youtube videos about how to save the image to local storage with Shared Preferences. And down below u can see another StackOverflow questions link where answered; how to save the image to local storage with Sqflite. – theiskaa Feb 06 '21 at 13:30
  • Thank you very much. I tried the Solution from your Link but it doesnt work for me. I can try your YT Videos. Thanks! – L.Ash Feb 06 '21 at 17:26
  • You’re Welcome dude! – theiskaa Feb 06 '21 at 17:27
  • Try found the solution for you in the another stackOverflov question which one i added on answer. – theiskaa Feb 06 '21 at 17:32