在 flutter 中将内容插入 sqflite 数据库后自动加载 UI 中的内容

Load content in UI automatically after inserting it in sqflite database in flutter

我有一些数据应该在按下按钮时存储在 SQLite 数据库中。 我希望它在我按下该按钮后立即显示在主屏幕上。 假设现在我在主屏幕上并且没有数据并且 UI 是空的。在按下按钮时,我转到另一个屏幕。按下按钮后,数据将插入到那里。当我返回主屏幕时插入后,我希望显示那些插入的数据。 这是我的插入方法和检索方法的代码。

Future<int> insert(Map<String, dynamic> row) async {
Database db = await instance.database;
return await db.insert(_tableName, row,
    conflictAlgorithm: ConflictAlgorithm.ignore);
}

Future<List<Favorite>> retrieveFavorite() async {
// Get a reference to the database.
final Database db = await database;

// Query the table for all The Dogs.
final List<Map> maps = await db.query(_tableName);
// List<Favorite> favorites=new List();
// maps.forEach((element) {
//   Favorite favorite=Favorite.fromMap(element);
//   favorites.add(favorite);
// });
return List.generate(maps.length, (i) {
  return Favorite(
      channelId: maps[i][columnChannelId],
      channelName: maps[i][columnChannelName],
      channelCategory: maps[i][columnChannelCategory],
      channelImage: maps[i][columnChannelImage],
      channelType: maps[i][columnChannelType],
      channelUrl: maps[i][columnChannelUrl],
      id: maps[i][columnId]);
  });
}

FutureBuilder<List<Favorite>>(
            future: DatabaseHelper.instance.retrieveFavorite(),
            builder: (BuildContext context,AsyncSnapshot<List<Favorite>> snapshot){
            return snapshot.hasData?
                Column(
                  children: [
                    snapshot.data.length>0?Row(

                      children: <Widget>[
                        Expanded(
                          child: Container(
                            margin: EdgeInsets.only(left: 10),
                            child: Text(
                              "Favorite Channels",
                              textAlign: TextAlign.left,
                              softWrap: true,
                              style: TextStyle(
                                  fontWeight: FontWeight.bold,
                                  fontSize: 12,
                                  decoration: TextDecoration.underline,
                                  decorationColor: Colors.red),
                              textScaleFactor: 1.5,
                            ),
                          ),
                        ),
                        (snapshot.data.length > 5)
                            ? Expanded(
                            child: InkWell(
                              onTap: () {
                                
                              },
                              child: Container(
                                padding: EdgeInsets.all(10),
                                child: Text(
                                  "See All",
                                  softWrap: true,
                                  textAlign: TextAlign.right,
                                  style: TextStyle(
                                    backgroundColor: Colors.red,
                                    color: Colors.white,
                                    // background:,
                                  ),
                                ),
                              ),
                            ))
                            : SizedBox(),
                      ],
                    ):SizedBox(),
                    snapshot.data.length>0?Row(//data from sqflite
                      children: <Widget>[
                        Expanded(
                          child: SizedBox(
                            height: 200.0,
                            child: ListView.separated(
                              //padding: const EdgeInsets.all(8),
                                addAutomaticKeepAlives: false,
                                scrollDirection: Axis.horizontal,
                                itemCount: snapshot.data.length,
                                itemBuilder: (BuildContext context, int index) {
                                  return (index < 6)
                                      ? InkWell(
                                    onTap: () {
                                      if (index == 5) {
                                        // Navigator.push(
                                        //     context,
                                        //     MaterialPageRoute(
                                        //         builder: (context) => GridPage(
                                        //           channel: channel,
                                        //         )));
                                      } else {
                                        //Navigator.push( context, MaterialPageRoute( builder: (context) => SecondPage()), ).then((value) => setState(() {}));
                                        // Navigator.push(
                                        //   context,
                                        //   MaterialPageRoute(
                                        //       builder: (context) => LiveTvPlayer(
                                        //         channel: channel[index],
                                        //       )),);
                                      }
                                    },
                                    child: Stack(
                                        alignment: Alignment.bottomCenter,
                                        children: [
                                          Container(
                                              margin: EdgeInsets.symmetric(
                                                  vertical: 10.0, horizontal: 3.0),
                                              height: 200,
                                              width: 200,
                                              child: (index == 5)
                                                  ? ImageBlur.network(
                                                snapshot.data[index].channelImage,
                                                scale: 2.5,
                                                height: 200,
                                                blur: 4,
                                                overlay: Column(
                                                  mainAxisAlignment: MainAxisAlignment.center,
                                                  children: [
                                                    //to be added icon
                                                    Icon(Icons.list,
                                                      size: 50,
                                                      color: Colors.white,
                                                    ),
                                                    Text(
                                                      "See More",
                                                      textAlign:
                                                      TextAlign.center,
                                                      style: TextStyle(

                                                        fontSize: 30,
                                                        color: Colors.white,
                                                      ),
                                                    ),
                                                    // Icon(Icons.list,
                                                    //   color: Colors.red,
                                                    //   // size: 10,
                                                    // ),
                                                  ],
                                                ),
                                                //bd[index].channelimage
                                              )
                                                  : Image.network(
                                                snapshot.data[index].channelImage,
                                              )

                                            //decoration: BoxDecoration(),

                                            //decoration: BoxDecoration,
                                          ),
                                          Container(
                                            color: Colors.black12,
                                            width: 200,
                                            height: 25,
                                            child: Text(
                                              snapshot.data[index].channelName,
                                              style: TextStyle(
                                                  fontWeight: FontWeight.bold,
                                                  fontSize: 20),
                                              textAlign: TextAlign.center,
                                            ),
                                          ),
                                        ]),
                                  )
                                      : SizedBox();
                                },
                                separatorBuilder: (BuildContext context, int index) =>
                                const Divider()),
                          ),
                        ),
                      ],
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    ):SizedBox()

                  ],
                )
                : SizedBox();
          },


          )

这可能不是执行此操作的最有效方法,但它确实有效。 我添加了下拉复习。它刷新页面的内容并显示它。 你可以在这里找到包 - Pull Down Refresh

    I have encountered the same issue when I use **futureBuilder** but it will work with out refreshing the page if you use Stream to get The data from the database.
// I Use this method to get the data from the db then Use **StreamBuilder** to List it out!
    {
     Stream<List<Name>> getAllItems() async* {
        final db = await _dbFuture;
        yield* db
            .createQuery(_tableItems)
            .mapToList((map) => Name.fromMap(map));
      }
    
    }