flutter - setState() or markNeedsBuild() called during build. Warning database has been locked for 0:00:10.000000 - Stack Overfl

I am trying to create a web blog with Hacker News API, but every time I try to run, I get this confusin

I am trying to create a web blog with Hacker News API, but every time I try to run, I get this confusing error thrown at me and I do not get it. asked chatgpt, it gave me a solution but I still run into the same error. I am pasting all necessary classes.

first this is my database class.

import 'dart:io';

import 'package:new_flutter/src/models/item_model.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';

final newsDbProv2 = NewsDbProv2();

class NewsDbProv2 {
  static const _dbName = "items.db";
  static const _dbVersion = 1;
  static const _tableName = "Items";

  Database? db;

  /// INITIALIZING THE DATABASE......
  Future<void> init() async {
    // if (db != null) return;
    if (db == null) {
      try {
        Directory documentsDirectory = await getApplicationDocumentsDirectory();
        final path = join(documentsDirectory.path, _dbName);
        db = await openDatabase(path,
            version: _dbVersion, onCreate: createTable);
      } catch (e) {
        print('Error initializing database: $e');
      }
    }
  }

  ///CREATING THE DATABASE TABLE........
  Future<void> createTable(Database newDb, int version) async {
    try {
      await newDb.execute("""
          CREATE TABLE $_tableName
          (
            id INTEGER PRIMARY KEY,
            type TEXT,
            by TEXT,
            time INTEGER,
            text TEXT,
            parent INTEGER,
            kids BLOB,
            dead INTEGER,
            deleted INTEGER,
            url TEXT,
            score INTEGER,
            title TEXT,
            descendants INTEGER
          )
          """);
    } catch (e) {
      print('Error creating table: $e');
    }
  }

  ///Fetching an ITEM by ID from the DATABASE.....
  Future<ItemModel?> fetchItem(int id) async {
    try {
      if (db == null) await init();

      final maps = await db!.query(
        _tableName,
        columns: null,
        where: "id = ?",
        whereArgs: [id],
      );

      if (maps.isNotEmpty) {
        return ItemModel.fromDB(maps.first);
      }
    } catch (e) {
      print('Error fetching item from the database: $e');
    }
    return null;
  }

  Future<int> addItem(ItemModel item) async {
    try {
      if (db == null) await init();

      return await db!.transaction((txn) async {
        return await txn.insert(
          // return db!.insert(
          _tableName,
          item.toMapForDb(),
          conflictAlgorithm: ConflictAlgorithm.ignore,
        );
      });
    } catch (e) {
      print('Error adding item to database: $e');
      return 0;
    }
  }

  // Future<int> addItem(ItemModel item) async {
  //   return await db!.transaction((txn) async {
  //     return await txn.insert(
  //       // return db!.insert(
  //       _tableName,
  //       item.toMapForDb(),
  //       conflictAlgorithm: ConflictAlgorithm.ignore,
  //     );
  //   });
  // }
}
// Future<List<int>> fetchTopIds() {
//   // TODO: implement fetchTopIds
//   throw UnimplementedError();
// }

this is the api class

import 'dart:convert';

import 'package:http/http.dart' show Client;
import 'package:new_flutter/src/models/item_model.dart';

const rootDomain = '';

class NewsApiProv2 {
  Client client = Client();

  /// Fetching Top story IDs from the API.......
  Future<List<int>> fetchTopIds() async {
    try {
      final response = await client
          .get(Uri.parse('$rootDomain/topstories.json'))
          .timeout(const Duration(seconds: 10));

      if (response.statusCode == 200) {
        final ids = json.decode(response.body);

        return ids.cast<int>();
      } else {
        print("Error: Failed to fetch top IDs. Status: ${response.statusCode}");
      }
    } catch (e) {
      print('Exception during fetchTopIds: $e');
    }
    return [];
  }

  /// Fetching a specific Story/ITEM by ID........
  Future<ItemModel?> fetchItem(int id) async {
    try {
      final response = await client
          .get(Uri.parse('$rootDomain/item/$id.json'))
          .timeout(const Duration(seconds: 10));
      if (response.statusCode == 200) {
        final parsedJson = json.decode(response.body);

        if (parsedJson == null || parsedJson.isEmpty) {
          print('Empty or null response for item with id $id');
          return null;
        }
        return ItemModel.fromJson(parsedJson);
      } else {
        print(
            'Failed to fetch item with id $id, Status Code: ${response.statusCode}');
        throw Exception('Failed to load item');
      }
    } catch (e) {
      print('Exception during fetchItem: $e');
    }
    return null;
  }
}

This is repository class:

import 'package:new_flutter/src/models/item_model.dart';
import 'package:new_flutter/src/resources/new_resource_dir/news_api_prov2.dart';
import 'package:new_flutter/src/resources/new_resource_dir/news_db_prov_2.dart';

class RepositoryProv2 {
  /// Initialize instances of the providers
  final NewsApiProv2 _newsApiProvider = NewsApiProv2();
  final NewsDbProv2 _newsDbProvider = NewsDbProv2();

  /// Fetch the top story IDs from the API
  Future<List<int>> fetchTopIds() async {
    try {
      return await _newsApiProvider.fetchTopIds();
    } catch (e) {
      print("Error fetching top IDs: $e");
      return [];
    }
  }

  /// Fetch an individual item from either API or Database (cache)
  Future<ItemModel?> fetchItems(int id) async {
    try {
      /// First try fetching the item from the database (cache)
      ItemModel? item = await _newsDbProvider.fetchItem(id);

      /// If the item is not found in the database, fetch from the API
      if (item == null) {
        item = await _newsApiProvider.fetchItem(id);

        /// If the item was found, save it in the database (cache)
        if (item != null) {
          await _newsDbProvider.addItem(item);
        }
      }
      return item;
    } catch (e) {
      print("Error fetching item: $e");
      return null;
    }
  }
}

This is my bloc class:

import 'package:flutter/cupertino.dart';
import 'package:new_flutter/src/models/item_model.dart';
import 'package:new_flutter/src/resources/new_resource_dir/repository_prov2.dart';

class NewsBloc extends ChangeNotifier {
  final RepositoryProv2 _prov2 = RepositoryProv2();

  List<int> _topIds = [];
  final List<ItemModel> _items = [];
  bool _isLoading = false;

  List<int> get topIds => _topIds;

  List<ItemModel> get items => _items;

  bool get isLoading => _isLoading;

  ///Fetch Top IDs from the API
  Future<void> fetchTopIds() async {
    _isLoading = true;
    notifyListeners(); //Notify UI to update

    try {
      _topIds = await _prov2.fetchTopIds();
    } catch (e) {
      print('Error fetching top IDs: $e');
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  /// Fetching ITEMS by IDs
  Future<ItemModel?> fetchItem(int id) async {
    _isLoading = true;
    notifyListeners();

    try {
      final item = await _prov2.fetchItems(id);
      if (item != null) {
        _items.add(item);
      }
    } catch (e) {
      print('Error fetching item: $e');
    } finally {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        _isLoading = false;
        notifyListeners();
      });
    }
    return null;
  }
}

this is the app.dart:

import 'package:flutter/material.dart';
import 'package:new_flutter/src/blocs/latest_bloc_provider/news_bloc.dart';
import 'package:new_flutter/src/screens/news_list.dart';
import 'package:provider/provider.dart';

class App extends StatelessWidget {
  const App({super.key});

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => NewsBloc(),
      child: MaterialApp(
        title: 'News!',
        home: NewsList(),
      ),
    );
  }
}

this is App.dart

import 'package:flutter/material.dart';
import 'package:new_flutter/src/blocs/latest_bloc_provider/news_bloc.dart';
import 'package:new_flutter/src/widgets/news_list_tile.dart';
import 'package:provider/provider.dart';

class NewsList extends StatelessWidget {
  const NewsList({super.key});

  @override
  Widget build(BuildContext context) {
    final bloc = Provider.of<NewsBloc>(context);

    ///Fetch Top IDs when the screen loads
    if (bloc.topIds.isEmpty) {
      bloc.fetchTopIds();
    }

    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: Colors.blue,
        elevation: 5,
        title: const Text(
          'Top News',
          style: TextStyle(
            color: Colors.white,
          ),
        ),
      ),
      body: buildList(bloc),
    );
  }

  Widget buildList(NewsBloc bloc) {
    return Consumer<NewsBloc>(
      builder: (context, bloc, child) {
        if (bloc.isLoading) {
          return Center(
            child: CircularProgressIndicator(color: Colors.blue),
          );
        }

        return ListView.builder(
          itemCount: bloc.topIds.length,
          itemBuilder: (context, int index) {
            return NewsListTile(
              itemId: bloc.topIds[index],
            );
          },
        );
      },
    );
  }
}

This is news list tile class:

import 'package:flutter/material.dart';
import 'package:new_flutter/src/models/item_model.dart';
import 'package:provider/provider.dart';

import '../blocs/latest_bloc_provider/news_bloc.dart';

class NewsListTile extends StatelessWidget {
  final int? itemId;

  const NewsListTile({super.key, this.itemId});

  @override
  Widget build(BuildContext context) {
    final bloc = Provider.of<NewsBloc>(context);

    return FutureBuilder<ItemModel?>(
      future: bloc.fetchItem(itemId!),
      builder: (context, snapshot) {
        // if (!snapshot.hasData) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return Text('Still loading item $itemId');
        }

        if (snapshot.hasError) {
          return Text('Error loading item $itemId: ${snapshot.error}');
        }
        if (!snapshot.hasData) {
          return Text('No data available');
        }
        return Text(snapshot.data!.title);
      },
    );
  }
}

The errors I am receiving from this is confusing and this is it:

======== Exception caught by foundation library ====================================================
The following assertion was thrown while dispatching notifications for NewsBloc:
setState() or markNeedsBuild() called during build.

This _InheritedProviderScope<NewsBloc?> widget cannot be marked as needing to build because the framework is already in the process of building widgets. A widget can be marked as needing to be built during the build phase only if one of its ancestors is currently building. This exception is allowed because the framework builds parent widgets before children, which means a dirty descendant will always be built. Otherwise, the framework might not visit this widget during this build phase.
The widget on which setState() or markNeedsBuild() was called was: _InheritedProviderScope<NewsBloc?>
  value: Instance of 'NewsBloc'
  listening to value
The widget which was currently being built when the offending call was made was: NewsListTile
  dirty
  dependencies: [_InheritedProviderScope<NewsBloc?>]
When the exception was thrown, this was the stack: 
#0      Element.markNeedsBuild.<anonymous closure> (package:flutter/src/widgets/framework.dart:5177:9)
#1      Element.markNeedsBuild (package:flutter/src/widgets/framework.dart:5189:6)
#2      _InheritedProviderScopeElement.markNeedsNotifyDependents (package:provider/src/inherited_provider.dart:577:5)
#3      ChangeNotifier.notifyListeners (package:flutter/src/foundation/change_notifier.dart:437:24)
#4      NewsBloc.fetchItem (package:new_flutter/src/blocs/latest_bloc_provider/news_bloc.dart:36:5)
#5      NewsListTile.build (package:new_flutter/src/widgets/news_list_tile.dart:17:20)
#6      StatelessElement.build (package:flutter/src/widgets/framework.dart:5687:49)
#7      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:5617:15)
The NewsBloc sending notification was: Instance of 'NewsBloc'
====================================================================================================
D/EGL_emulation(13392): app_time_stats: avg=1797.18ms min=1797.18ms max=1797.18ms count=1
I/flutter (13392): Warning database has been locked for 0:00:10.000000. Make sure you always use the transaction object for database operations during a transaction
I/flutter (13392): Warning database has been locked for 0:00:10.000000. Make sure you always use the transaction object for database operations during a transaction
I/flutter (13392): Warning database has been locked for 0:00:10.000000. Make sure you always use the transaction object for database operations during a transaction
I/flutter (13392): Warning database has been locked for 0:00:10.000000. Make sure you always use the transaction object for database operations during a transaction
I/flutter (13392): Warning database has been locked for 0:00:10.000000. Make sure you always use the transaction object for database operations during a transaction
I/flutter (13392): Warning database has been locked for 0:00:10.000000. Make sure you always use the transaction object for database operations during a transaction

I am trying to create a web blog with Hacker News API, but every time I try to run, I get this confusing error thrown at me and I do not get it. asked chatgpt, it gave me a solution but I still run into the same error. I am pasting all necessary classes.

first this is my database class.

import 'dart:io';

import 'package:new_flutter/src/models/item_model.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';

final newsDbProv2 = NewsDbProv2();

class NewsDbProv2 {
  static const _dbName = "items.db";
  static const _dbVersion = 1;
  static const _tableName = "Items";

  Database? db;

  /// INITIALIZING THE DATABASE......
  Future<void> init() async {
    // if (db != null) return;
    if (db == null) {
      try {
        Directory documentsDirectory = await getApplicationDocumentsDirectory();
        final path = join(documentsDirectory.path, _dbName);
        db = await openDatabase(path,
            version: _dbVersion, onCreate: createTable);
      } catch (e) {
        print('Error initializing database: $e');
      }
    }
  }

  ///CREATING THE DATABASE TABLE........
  Future<void> createTable(Database newDb, int version) async {
    try {
      await newDb.execute("""
          CREATE TABLE $_tableName
          (
            id INTEGER PRIMARY KEY,
            type TEXT,
            by TEXT,
            time INTEGER,
            text TEXT,
            parent INTEGER,
            kids BLOB,
            dead INTEGER,
            deleted INTEGER,
            url TEXT,
            score INTEGER,
            title TEXT,
            descendants INTEGER
          )
          """);
    } catch (e) {
      print('Error creating table: $e');
    }
  }

  ///Fetching an ITEM by ID from the DATABASE.....
  Future<ItemModel?> fetchItem(int id) async {
    try {
      if (db == null) await init();

      final maps = await db!.query(
        _tableName,
        columns: null,
        where: "id = ?",
        whereArgs: [id],
      );

      if (maps.isNotEmpty) {
        return ItemModel.fromDB(maps.first);
      }
    } catch (e) {
      print('Error fetching item from the database: $e');
    }
    return null;
  }

  Future<int> addItem(ItemModel item) async {
    try {
      if (db == null) await init();

      return await db!.transaction((txn) async {
        return await txn.insert(
          // return db!.insert(
          _tableName,
          item.toMapForDb(),
          conflictAlgorithm: ConflictAlgorithm.ignore,
        );
      });
    } catch (e) {
      print('Error adding item to database: $e');
      return 0;
    }
  }

  // Future<int> addItem(ItemModel item) async {
  //   return await db!.transaction((txn) async {
  //     return await txn.insert(
  //       // return db!.insert(
  //       _tableName,
  //       item.toMapForDb(),
  //       conflictAlgorithm: ConflictAlgorithm.ignore,
  //     );
  //   });
  // }
}
// Future<List<int>> fetchTopIds() {
//   // TODO: implement fetchTopIds
//   throw UnimplementedError();
// }

this is the api class

import 'dart:convert';

import 'package:http/http.dart' show Client;
import 'package:new_flutter/src/models/item_model.dart';

const rootDomain = 'https://hacker-news.firebaseio/v0';

class NewsApiProv2 {
  Client client = Client();

  /// Fetching Top story IDs from the API.......
  Future<List<int>> fetchTopIds() async {
    try {
      final response = await client
          .get(Uri.parse('$rootDomain/topstories.json'))
          .timeout(const Duration(seconds: 10));

      if (response.statusCode == 200) {
        final ids = json.decode(response.body);

        return ids.cast<int>();
      } else {
        print("Error: Failed to fetch top IDs. Status: ${response.statusCode}");
      }
    } catch (e) {
      print('Exception during fetchTopIds: $e');
    }
    return [];
  }

  /// Fetching a specific Story/ITEM by ID........
  Future<ItemModel?> fetchItem(int id) async {
    try {
      final response = await client
          .get(Uri.parse('$rootDomain/item/$id.json'))
          .timeout(const Duration(seconds: 10));
      if (response.statusCode == 200) {
        final parsedJson = json.decode(response.body);

        if (parsedJson == null || parsedJson.isEmpty) {
          print('Empty or null response for item with id $id');
          return null;
        }
        return ItemModel.fromJson(parsedJson);
      } else {
        print(
            'Failed to fetch item with id $id, Status Code: ${response.statusCode}');
        throw Exception('Failed to load item');
      }
    } catch (e) {
      print('Exception during fetchItem: $e');
    }
    return null;
  }
}

This is repository class:

import 'package:new_flutter/src/models/item_model.dart';
import 'package:new_flutter/src/resources/new_resource_dir/news_api_prov2.dart';
import 'package:new_flutter/src/resources/new_resource_dir/news_db_prov_2.dart';

class RepositoryProv2 {
  /// Initialize instances of the providers
  final NewsApiProv2 _newsApiProvider = NewsApiProv2();
  final NewsDbProv2 _newsDbProvider = NewsDbProv2();

  /// Fetch the top story IDs from the API
  Future<List<int>> fetchTopIds() async {
    try {
      return await _newsApiProvider.fetchTopIds();
    } catch (e) {
      print("Error fetching top IDs: $e");
      return [];
    }
  }

  /// Fetch an individual item from either API or Database (cache)
  Future<ItemModel?> fetchItems(int id) async {
    try {
      /// First try fetching the item from the database (cache)
      ItemModel? item = await _newsDbProvider.fetchItem(id);

      /// If the item is not found in the database, fetch from the API
      if (item == null) {
        item = await _newsApiProvider.fetchItem(id);

        /// If the item was found, save it in the database (cache)
        if (item != null) {
          await _newsDbProvider.addItem(item);
        }
      }
      return item;
    } catch (e) {
      print("Error fetching item: $e");
      return null;
    }
  }
}

This is my bloc class:

import 'package:flutter/cupertino.dart';
import 'package:new_flutter/src/models/item_model.dart';
import 'package:new_flutter/src/resources/new_resource_dir/repository_prov2.dart';

class NewsBloc extends ChangeNotifier {
  final RepositoryProv2 _prov2 = RepositoryProv2();

  List<int> _topIds = [];
  final List<ItemModel> _items = [];
  bool _isLoading = false;

  List<int> get topIds => _topIds;

  List<ItemModel> get items => _items;

  bool get isLoading => _isLoading;

  ///Fetch Top IDs from the API
  Future<void> fetchTopIds() async {
    _isLoading = true;
    notifyListeners(); //Notify UI to update

    try {
      _topIds = await _prov2.fetchTopIds();
    } catch (e) {
      print('Error fetching top IDs: $e');
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  /// Fetching ITEMS by IDs
  Future<ItemModel?> fetchItem(int id) async {
    _isLoading = true;
    notifyListeners();

    try {
      final item = await _prov2.fetchItems(id);
      if (item != null) {
        _items.add(item);
      }
    } catch (e) {
      print('Error fetching item: $e');
    } finally {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        _isLoading = false;
        notifyListeners();
      });
    }
    return null;
  }
}

this is the app.dart:

import 'package:flutter/material.dart';
import 'package:new_flutter/src/blocs/latest_bloc_provider/news_bloc.dart';
import 'package:new_flutter/src/screens/news_list.dart';
import 'package:provider/provider.dart';

class App extends StatelessWidget {
  const App({super.key});

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => NewsBloc(),
      child: MaterialApp(
        title: 'News!',
        home: NewsList(),
      ),
    );
  }
}

this is App.dart

import 'package:flutter/material.dart';
import 'package:new_flutter/src/blocs/latest_bloc_provider/news_bloc.dart';
import 'package:new_flutter/src/widgets/news_list_tile.dart';
import 'package:provider/provider.dart';

class NewsList extends StatelessWidget {
  const NewsList({super.key});

  @override
  Widget build(BuildContext context) {
    final bloc = Provider.of<NewsBloc>(context);

    ///Fetch Top IDs when the screen loads
    if (bloc.topIds.isEmpty) {
      bloc.fetchTopIds();
    }

    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: Colors.blue,
        elevation: 5,
        title: const Text(
          'Top News',
          style: TextStyle(
            color: Colors.white,
          ),
        ),
      ),
      body: buildList(bloc),
    );
  }

  Widget buildList(NewsBloc bloc) {
    return Consumer<NewsBloc>(
      builder: (context, bloc, child) {
        if (bloc.isLoading) {
          return Center(
            child: CircularProgressIndicator(color: Colors.blue),
          );
        }

        return ListView.builder(
          itemCount: bloc.topIds.length,
          itemBuilder: (context, int index) {
            return NewsListTile(
              itemId: bloc.topIds[index],
            );
          },
        );
      },
    );
  }
}

This is news list tile class:

import 'package:flutter/material.dart';
import 'package:new_flutter/src/models/item_model.dart';
import 'package:provider/provider.dart';

import '../blocs/latest_bloc_provider/news_bloc.dart';

class NewsListTile extends StatelessWidget {
  final int? itemId;

  const NewsListTile({super.key, this.itemId});

  @override
  Widget build(BuildContext context) {
    final bloc = Provider.of<NewsBloc>(context);

    return FutureBuilder<ItemModel?>(
      future: bloc.fetchItem(itemId!),
      builder: (context, snapshot) {
        // if (!snapshot.hasData) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return Text('Still loading item $itemId');
        }

        if (snapshot.hasError) {
          return Text('Error loading item $itemId: ${snapshot.error}');
        }
        if (!snapshot.hasData) {
          return Text('No data available');
        }
        return Text(snapshot.data!.title);
      },
    );
  }
}

The errors I am receiving from this is confusing and this is it:

======== Exception caught by foundation library ====================================================
The following assertion was thrown while dispatching notifications for NewsBloc:
setState() or markNeedsBuild() called during build.

This _InheritedProviderScope<NewsBloc?> widget cannot be marked as needing to build because the framework is already in the process of building widgets. A widget can be marked as needing to be built during the build phase only if one of its ancestors is currently building. This exception is allowed because the framework builds parent widgets before children, which means a dirty descendant will always be built. Otherwise, the framework might not visit this widget during this build phase.
The widget on which setState() or markNeedsBuild() was called was: _InheritedProviderScope<NewsBloc?>
  value: Instance of 'NewsBloc'
  listening to value
The widget which was currently being built when the offending call was made was: NewsListTile
  dirty
  dependencies: [_InheritedProviderScope<NewsBloc?>]
When the exception was thrown, this was the stack: 
#0      Element.markNeedsBuild.<anonymous closure> (package:flutter/src/widgets/framework.dart:5177:9)
#1      Element.markNeedsBuild (package:flutter/src/widgets/framework.dart:5189:6)
#2      _InheritedProviderScopeElement.markNeedsNotifyDependents (package:provider/src/inherited_provider.dart:577:5)
#3      ChangeNotifier.notifyListeners (package:flutter/src/foundation/change_notifier.dart:437:24)
#4      NewsBloc.fetchItem (package:new_flutter/src/blocs/latest_bloc_provider/news_bloc.dart:36:5)
#5      NewsListTile.build (package:new_flutter/src/widgets/news_list_tile.dart:17:20)
#6      StatelessElement.build (package:flutter/src/widgets/framework.dart:5687:49)
#7      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:5617:15)
The NewsBloc sending notification was: Instance of 'NewsBloc'
====================================================================================================
D/EGL_emulation(13392): app_time_stats: avg=1797.18ms min=1797.18ms max=1797.18ms count=1
I/flutter (13392): Warning database has been locked for 0:00:10.000000. Make sure you always use the transaction object for database operations during a transaction
I/flutter (13392): Warning database has been locked for 0:00:10.000000. Make sure you always use the transaction object for database operations during a transaction
I/flutter (13392): Warning database has been locked for 0:00:10.000000. Make sure you always use the transaction object for database operations during a transaction
I/flutter (13392): Warning database has been locked for 0:00:10.000000. Make sure you always use the transaction object for database operations during a transaction
I/flutter (13392): Warning database has been locked for 0:00:10.000000. Make sure you always use the transaction object for database operations during a transaction
I/flutter (13392): Warning database has been locked for 0:00:10.000000. Make sure you always use the transaction object for database operations during a transaction
Share Improve this question asked Nov 17, 2024 at 3:31 Fred_WolfeFred_Wolfe 8722 gold badges11 silver badges22 bronze badges 3
  • most likely it happens since you are calling notifyListeners inside fetchItems method: it forces another rebuild while building your NewsListTile – pskink Commented Nov 17, 2024 at 7:46
  • you are saying the same thing ChatGPT said brother. still no fix. What is the way around – Fred_Wolfe Commented Nov 17, 2024 at 8:00
  • I am getting a new error now... or more like a warning: I/flutter (14787): Warning database has been locked for 0:00:10.000000. Make sure you always use the transaction object for database operations during a transaction – Fred_Wolfe Commented Nov 17, 2024 at 10:11
Add a comment  | 

1 Answer 1

Reset to default 1

According to

#4 NewsBloc.fetchItem (package:new_flutter/src/blocs/latest_bloc_provider/news_bloc.dart:36:5)

the error occurred in bloc class NewsBloc line 36, wrap notifyListeners() in WidgetsBinding.instance.addPostFrameCallback might solve this problem.

  /// Fetching ITEMS by IDs
  Future<ItemModel?> fetchItem(int id) async {
    _isLoading = true;
    WidgetsBinding.instance.addPostFrameCallback((_) {
      notifyListeners();
    });

    try {
      final item = await _prov2.fetchItems(id);
      if (item != null) {
        _items.add(item);
      }
    } catch (e) {
      print('Error fetching item: $e');
    } finally {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        _isLoading = false;
        notifyListeners();
      });
    }
    return null;
  }

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745639600a4637606.html

相关推荐

  • 国产之光!!让你的Docker管理更优雅!

    大家好,我是热爱开源的了不起!我们都知道,Docker是个好东西,能帮我们把应用打包成容器,方便部署和管理。但问题来了,Docker的命令行操作对新手来说有点复杂,一不小心就容易出错。而且,有时候我们只是想简单地管理一下容器,却得记住一堆命

    1小时前
    00
  • 面试官:从三万英尺角度谈一下Ceph架构设计(1)

    把面试官当陪练,在找工作中才会越战越勇大家好我是小义同学,这是大厂面试拆解——项目实战系列的第3篇文章,如果有误,请指正。本文主要解决的一个问题,Ceph为例子 如何描述项目的架构。一句话描述:主要矛盾发生变化10年前的技术和方案,放到10

    1小时前
    00
  • 电脑开机会默认一件GHOST

    关于电脑开机会自己重装系统 前段时间电脑一开机就遇到会自己ghost的问题&#xff0c;而且一直再重复同样的操作&#xff0c;我点击restart的时候到开启页面又会自动ghost&#xff0c;而且此页面停留

    1小时前
    00
  • 长读长测序揭示结直肠癌异常可变剪接图谱与新型治疗靶点

    徐州医科大学肿瘤研究所董东郑骏年教授团队在Genome Medicine杂志发表题为“Long-read sequencing reveals the landscape of aberrant alternative splicing

    1小时前
    00
  • ascend pytorch 踩坑.

    在910b上安装pytorch 和 pytorch_npu, 因为后续准备装vllm, 所以torch_npu是特殊的版本.代码语言:shell复制pip install torch==2.5.1 --extra-index pip in

    53分钟前
    00
  • Go 语言 Mock 实践

    Mock 是软件测试中的一项关键技术,尤其在单元测试领域,可谓是“顶梁柱”般的存在,几乎不可或缺。它通过模拟真实对象的行为,使我们能在不依赖外部系统的情况下,专注测试代码的核心逻辑。对于测试开发、自动化测试,乃至性能测试中的某些场景,合理使

    49分钟前
    00
  • CUT&amp;amp;Tag 数据处理和分析教程(7)

    过滤某些项目可能需要对比对质量分数进行更严格的过滤。本文细讨论了bowtie如何分配质量分数,并举例说明。MAPQ(x) = -10 * log10log10(P(x is mapped wrongly)) = -10 * log10(p)

    44分钟前
    10
  • UCB的硅光MEMS OCS控制技术

    昨天写的旭创与nEye合作了一个64端口硅光OCS一、光电路交换技术概述(一)电交换与分组交换电路交换的概念源于早期的电话交换机,通过物理连接实现设备间的通信,就像早期打电话时,接线员手动连接线路一样。而分组交换则是

    39分钟前
    00
  • 推荐一个轻量级的监控平台并且支持移动端

    简介XUGOU 是基于Cloudflare构建的轻量化监控平台,专精于系统资源监控与可视化状态页面服务。该平台提供英文简体中文双语支持,满足全球化部署需求。面向开发者及中小团队,项目致力于提供高可用性的监控解决方案。核心功能与实现平台功能

    38分钟前
    00
  • 【Docker项目实战】使用Docker部署IT工具箱Team·IDE

    一、Team·IDE介绍1.1 Team·IDE简介Team IDE 是一款集成多种数据库(如 MySQL、Oracle、金仓、达梦、神通等)与分布式系统组件(如 Redis、Zookeeper、Kafka、Elasticsearch)管理

    34分钟前
    00
  • Windows Server20192022 Evaluation评估版未激活导致关机问题

    摘要&#xff1a;在安装Windows Server 20192022后&#xff0c;会出现系统版本为 Evaluation 评估版情况&#xff0c;如提示Windows许可证已到期&#xff0c;就

    28分钟前
    00
  • 人工智能与ai有什么区别

    一、引言:概念之辨的必要性在科技浪潮席卷全球的当下,人工智能(Artificial Intelligence,简称AI)已成为人们耳熟能详的词汇。然而,当我们深入探讨时,会发现“人工智能”与“AI”这两个表述在语义和使用场景上存在微妙差异。

    28分钟前
    00
  • windows新建open ai密钥

    api链接 openai的api需要付费才能使用但好像系统变量不知道为啥用不了打印出来&#xff0c;获取到的是None可以用了

    24分钟前
    00
  • Windows系统密钥检测工具PIDKey 2.1中文版

    Windows系统密钥检测工具PIDKey 2.1中文版 【下载地址】Windows系统密钥检测工具PIDKey2.1中文版 Windows系统密钥检测工具PIDKey 2.1中文版是一款功能强大的工具&#xff0c;专为管理Win

    21分钟前
    00
  • 人工智能应用领域有哪些

    人工智能应用领域有哪些一、引言随着科技的飞速发展,人工智能(AI)已经逐渐渗透到我们生活的方方面面,成为推动社会进步的重要力量。从医疗健康到金融服务,从教育学习到智能制造,人工智能以其独特的技术优势,为各行各业带来了前所未有的变革。本文旨在

    14分钟前
    10
  • windows切换系统版本

    powershell 管理员身份打开 输入 irm massgrave.devget | iex 输入数字 对应后面写着 change windows edition新的会话框中选择想要的版本即可 获取windows 密钥 官方提供的

    12分钟前
    00
  • 在Windows上使用MetaMCP的完整指南

    在当今AI助手工具快速发展的时代&#xff0c;如何有效管理各种MCP&#xff08;Model Control Protocol&#xff09;服务成为了一个挑战。MetaMCP应运而生&#xff0c;它是

    9分钟前
    00
  • 解决Windows 10家庭单语言版语言限制:升级专业版全攻略

    解决Windows 10家庭单语言版语言限制:升级专业版全攻略 在日常使用Windows 10系统时,部分用户可能会遇到系统提示“当前许可证仅支持单一显示语言”的困扰。这一问题通常出现在预装或激活了Windows 10家庭单语言版的设备上

    7分钟前
    00
  • OpenAI“Agent 圣经”翻车?LangChain 创始人怒怼“全是坑”!

    整理 | Tina当前,AI 领域呈现出一种近乎“追星式”的热情氛围,每当有新的东西发布,便迅速引发广泛关注与高度评价,仿佛技术变革即将一触即发。同时大家情绪也波动剧烈,从“危机论”到“爆发论”频繁切换。OpenAI 最近出的《A Pra

    4分钟前
    00
  • AI也要007?Letta、伯克利提出「睡眠时间计算」,推理效率翻倍还不加钱

    机器之心报道编辑:+0、陈陈AI 也要 007 工作制了!近日,AI 初创公司 Letta 和 UC 伯克利的研究人员提出了一种扩展人工智能能力的新方式 —— 睡眠时间计算(Sleep-time Compute),让模型在空闲时间「思考」,

    1分钟前
    00

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信