为什么使用 sqflite 删除行在 flutter 中不起作用?

问题描述 投票:0回答:1

我在删除应用程序中的行时遇到问题,它删除时没有错误,但在获取数据时它仍然存在,就像它从未被删除一样 我正在使用 sqflite 包 这是获取数据库的函数:

  Future<Database> _getDatabase() async {
    final dbPath = await sql.getDatabasesPath();
    print('get database path');
    final db = await sql.openDatabase(
      path.join(dbPath, 'placesFav.db'),
      onCreate: (db, version) {
        print('creating table');
        return db.execute(
            'CREATE TABLE $_tableName(id TEXT PRIMARY KEY, title TEXT, image TEXT, lat REAL, lng REAL, address TEXT)');
      },
      version: 1,
    );
    return db;
  }

这是从数据库获取数据的函数:

  Future<void> getPlaces() async {
    final db = await _getDatabase();
    final dataOfDb = await db.query(
      _tableName,
    );
    state = dataOfDb
        .map(
          (row) => FavoritePlace(
            id: row['id'] as String,
            title: row['title'] as String,
            image: File(row['image'] as String),
            favLocation: FavoriteLocation(
              latitude: row['lat'] as double,
              longitude: row['lng'] as double,
              address: row['address'] as String,
            ),
          ),
        )
        .toList();

    await db.close();
  }

这是删除行功能:

Future<void> removePlace(FavoritePlace favPlace) async {
    state = state.where((place) => place.id != favPlace.id).toList();
    final db = await _getDatabase();
    final data =
        await db.delete(_tableName, where: 'id = ?', whereArgs: [favPlace.id]);
    print(data);
    await favPlace.image.delete();
    await db.close();
  }
}

这是添加地点功能:

void addPlace(FavoritePlace favPlace) async {
    final appDir = await app_path.getApplicationDocumentsDirectory();
    final imageName = path.basename(favPlace.image.path);
    final cImage =
        await favPlace.image.copy('${appDir.path}/${favPlace.id[3]}$imageName');
    state = [...state, favPlace];
    final db = await _getDatabase();
    await db.insert(_tableName, {
      'id': favPlace.id,
      'title': favPlace.title,
      'image': cImage.path,
      'lat': favPlace.favLocation.latitude,
      'lng': favPlace.favLocation.longitude,
      'address': favPlace.favLocation.address,
    });
    await db.close();
    print('db closed');
  }

这是我使用它的地方:

class _HomeScreenStateConsumer extends ConsumerState<HomeScreen> {
  List<FavoritePlace> favList = [];
  late Future<void> _loadPlaces;
  AppBar _appBar(BuildContext context) {
    return AppBar(
      actions: [
        IconButton(
          onPressed: () async {
            final favPlace = await Navigator.of(context)
                .push<FavoritePlace>(MaterialPageRoute(builder: (ctx) {
              return const AddNewPlace();
            }));
            if (favPlace == null) {
              return;
            }
          },
          icon: const Icon(Icons.add),
        ),
      ],
      title: const Text('Favorite places'),
    );
  }

  @override
  void initState() {
    _loadPlaces = ref.read(favoritePlaceProvider.notifier).getPlaces();
    super.initState();
  }

  Future<void> _getRefresh() async {
      await ref.read(favoritePlaceProvider.notifier).getPlaces();
  }

  @override
  Widget build(BuildContext context) {
    final height = MediaQuery.of(context).size.height -
        _appBar(context).preferredSize.height -
        MediaQuery.of(context).padding.top;
    favList = ref.watch(favoritePlaceProvider);
    print(favList.length);
    return Scaffold(
      appBar: _appBar(context),
      body: RefreshIndicator(
        onRefresh: _getRefresh,
        triggerMode: RefreshIndicatorTriggerMode.onEdge,
        child: FutureBuilder(
          future: _loadPlaces,
          builder: (context, snapshot) => snapshot.connectionState ==
                  ConnectionState.waiting
              ? const Center(
                  child: CircularProgressIndicator(),
                )
              : favList.isEmpty
                  ? SingleChildScrollView(
            physics: const AlwaysScrollableScrollPhysics(),
                    child: Container(
                      height: height,
                      alignment: Alignment.center,
                      child: Text(
                          'There is no places to see',
                          style: Theme.of(context)
                              .textTheme
                              .titleMedium!
                              .copyWith(
                                color: Colors.white,
                              ),
                        ),
                      ),
                  )
                  : Padding(
                      padding: EdgeInsets.all(8),
                      child: ListView.builder(
                        itemCount: favList.length,
                        itemBuilder: (ctx, index) {
                          print(favList[index].title);
                          return Dismissible(
                              key: ValueKey(favList[index].id),
                              direction: DismissDirection.horizontal,
                              onDismissed: (_) async {
                                setState(() {
                                  ref
                                      .read(favoritePlaceProvider.notifier)
                                      .removePlace(favList[index]);
                                });
                              },
                              child:
                                  FavoriteItem(favPlace: favList[index]));
                        },
                      ),
                    ),
        ),
      ),
    );
  }
}

我期待该行被删除,但它在应用程序中删除了,但是当再次获取时它再次出现,因为:

await favPlace.image.delete();

重新加载时出现错误,因为文件中的图像被删除

那么为什么会发生这种情况?

flutter dart path sqflite mobile-development
1个回答
0
投票

问题会解决吗..我使用

uuid
包来使用 id 的通用唯一标识符,因此当我使用此
uuid
id 制作新项目时,它会使其唯一,但在通过
get()
获取它时无法获取所以当我使用
delete()
函数删除它时,它并没有从数据库中删除

所以我使用

DateTime.now().toIso8601String()
作为 ID,效果很好。

© www.soinside.com 2019 - 2024. All rights reserved.