首页 > 解决方案 > 如何在颤振中修复工厂 DbHelper 类?

问题描述

我在颤振运行时出错。应该是有问题

  //podesavanje singltona 2/3
  DbHelper()._internal();
  //podesavanje singltona 3/3
  factory DbHelper() {
    return _dbHelper;
  }

在 dbhelper.dart 文件中。知道如何解决吗?

dbhelper.dart

import 'package:sqflite/sqflite.dart';
import 'dart:async';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:todo_app/model/todo.dart';

class DbHelper {
  //podesavanje singltona 1/3
  static final DbHelper _dbHelper = DbHelper()._internal();
  //table name
  String tblName = "todo";
  //columns
  String colId = "id";
  String colTitle = "title";
  String colDescription = "description";
  String colPriority = "priority";
  String colDate = "date";
  //podesavanje singltona 2/3
  DbHelper()._internal();
  //podesavanje singltona 3/3
  factory DbHelper() {
    return _dbHelper;
  }
  
  static Database _db;
  Future<Database> get db async {
    if (_db == null) {
      _db = await initializeDb();
    }
    return _db;
  }

  //za ovo koristimo 'dart:io';
  Future<Database> initializeDb() async {

    Directory dir = await getApplicationDocumentsDirectory();
    String path = dir.path + "todos.db";
    var dbTodos = await openDatabase(path, version: 1, onCreate: _createDb);
    return dbTodos;
  }
  void _createDb(Database db, int newVersion) async {
    await db.execute(
      "CREATE TABLE $tblName($colId INTEGER PRIMARY KEY, $colTitle TEXT, $colDescription TEXT, $colPriority INTEGER, $colDate TEXT)"
      );
  }

  Future<int> insertTodo(Todo todo) async{
    Database db = await this.db;
    var result = await db.insert(tblName, todo.toMap());
    return result;
  }
  Future<List> getTodos() async {
    Database db = await this.db;
    var result = await db.rawQuery("SELECT * FROM $tblName order by $colPriority ASC");
    return result;
  }
  Future<int> getCount() async {
    Database db = await this.db;
    var result = Sqflite.firstIntValue(
          await db.rawQuery("SELECT COUNT(*) FROM $tblName")
    );
    return result;
  }
  Future<int> updateTodo(Todo todo) async{
    Database db = await this.db;
    var result = await db.update(tblName, todo.toMap(), where: "$colId = ?", whereArgs: [todo.id]);
    return result;
  }
  Future<int> deleteTodo(int id) async{
    Database db = await this.db;
    var result = await db.rawDelete("DELETE FROM $tblName WHERE $colId =  $id");
    return result;
  }

}

todo.dart

import 'package:flutter/scheduler.dart';

class Todo {
  //_ se stavlja zato da budu privatni
  int _id;
  String _title;
  String _description;
  String _date;
  int _priority;
  //postavljanje konstruktora, ne moze isti vise puta, opcioni ide u []
  Todo(this._title, this._priority, this._date, [this._description]);
  Todo.withId(this._id, this._title, this._priority, this._date,
      [this._description]);
  //geteri
  int get id => _id;
  String get title => _title;
  String get description => _description;
  String get date => _date;
  int get priority => _priority;
  //seteri
  set title(String newTitle) {
    if (newTitle.length < 255) {
      _title = newTitle;
    }
  }

  set description(String newDescription) {
    if (newDescription.length < 255) {
      _description = newDescription;
    }
  }

  set priority(int newPriority) {
    if (newPriority > 0 && newPriority <= 3) {
      _priority = newPriority;
    }
  }

  set date(String newDate) {
    _date = newDate;
  }

  Map<String, dynamic> toMap() {
    var map = Map<String, dynamic>();
    map["title"] = _title;
    map["description"] = _description;
    map["priority"] = _priority;
    map["date"] = _date;

    if (_id != null) {
      map["id"] = _id;
    }

    return map;
  }

  Todo.fromObject(dynamic o) {
    this._id = o["id"];
    this._title = o["title"];
    this._description = o["description"];
    this._date = o["date"];
    this._priority = o["priority"];
  }
}

主要.dart

import 'package:flutter/material.dart';
import 'package:todo_app/util/dbhelper.dart';
import 'package:todo_app/model/todo.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    List<Todo> todos = List<Todo>();
    DbHelper helper = DbHelper();
    helper
        .initializeDb()
        .then((result) => helper.getTodos().then((result) => todos = result));

    DateTime today = DateTime.now();
    Todo todo = Todo("naslov", 1, today.toString(), "opcioni diskripsn");
    helper.insertTodo(todo);
  }
}

扑跑

Launching lib/main.dart on iPhone 8 Plus in debug mode...
Running Xcode build...                                                  
Xcode build done.                                           10.4s
Failed to build iOS app
Error output from Xcode build:
↳
    ** BUILD FAILED **


Xcode's output:
↳
    lib/util/dbhelper.dart:19:13: Error: Expected '{' before this.
      DbHelper()._internal();
                ^
    lib/util/dbhelper.dart:19:13: Error: Expected a class member, but got '.'.
      DbHelper()._internal();
                ^
    lib/util/dbhelper.dart:21:11: Error: 'DbHelper' is already declared in this scope.
      factory DbHelper() {
              ^^^^^^^^
    lib/util/dbhelper.dart:19:3: Context: Previous declaration of 'DbHelper'.
      DbHelper()._internal();
      ^^^^^^^^
    lib/util/dbhelper.dart:7:7: Error: The non-abstract class 'DbHelper' is missing implementations for these members:
     - DbHelper._internal
    Try to either
     - provide an implementation,
     - inherit an implementation from a superclass or mixin,
     - mark the class as abstract, or
     - provide a 'noSuchMethod' implementation.

    class DbHelper {
          ^^^^^^^^
    lib/util/dbhelper.dart:19:14: Context: 'DbHelper._internal' is defined here.
      DbHelper()._internal();
                 ^^^^^^^^^
    lib/main.dart:14:23: Error: Can't use 'DbHelper' because it is declared more than once.
        DbHelper helper = DbHelper();
                          ^
    lib/util/dbhelper.dart:9:37: Error: Can't use 'DbHelper' because it is declared more than once.
      static final DbHelper _dbHelper = DbHelper()._internal();
                                        ^

    Command PhaseScriptExecution failed with a nonzero exit code
    note: Using new build systemnote: Planning buildnote: Constructing build description

标签: flutterdart

解决方案


这就是你想要做的


class DbHelper {
  //podesavanje singltona 1/3
  static final DbHelper _dbHelper = DbHelper._internal();
  //table name
  String tblName = "todo";
  //columns
  String colId = "id";
  String colTitle = "title";
  String colDescription = "description";
  String colPriority = "priority";
  String colDate = "date";
  //podesavanje singltona 2/3
  DbHelper._internal();
  //podesavanje singltona 3/3
  factory DbHelper() {
    return _dbHelper;
  }

  static Database _db;
  Future<Database> get db async {
    if (_db == null) {
      _db = await initializeDb();
    }
    return _db;
  }

  //za ovo koristimo 'dart:io';
  Future<Database> initializeDb() async {
    Directory dir = await getApplicationDocumentsDirectory();
    String path = dir.path + "todos.db";
    var dbTodos = await openDatabase(path, version: 1, onCreate: _createDb);
    return dbTodos;
  }

  void _createDb(Database db, int newVersion) async {
    await db.execute(
        "CREATE TABLE $tblName($colId INTEGER PRIMARY KEY, $colTitle TEXT, $colDescription TEXT, $colPriority INTEGER, $colDate TEXT)");
  }

  Future<int> insertTodo(Todo todo) async {
    Database db = await this.db;
    var result = await db.insert(tblName, todo.toMap());
    return result;
  }

  Future<List> getTodos() async {
    Database db = await this.db;
    var result =
        await db.rawQuery("SELECT * FROM $tblName order by $colPriority ASC");
    return result;
  }

  Future<int> getCount() async {
    Database db = await this.db;
    var result = Sqflite.firstIntValue(
        await db.rawQuery("SELECT COUNT(*) FROM $tblName"));
    return result;
  }

  Future<int> updateTodo(Todo todo) async {
    Database db = await this.db;
    var result = await db.update(tblName, todo.toMap(),
        where: "$colId = ?", whereArgs: [todo.id]);
    return result;
  }

  Future<int> deleteTodo(int id) async {
    Database db = await this.db;
    var result = await db.rawDelete("DELETE FROM $tblName WHERE $colId =  $id");
    return result;
  }
}

推荐阅读