Search code examples
flutterwidgetsqflitestateful

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


I have some data that should be stored on an SQLite database on button press. I want it to be shown on the main screen as soon as I press that button. Suppose now I am on the main screen and I don't have the data and the UI is empty. On a button pressed I go to another screen. The data is inserted there on a button press. After inserting when I come back to the main screen I want those inserted data shown. Here is the code of my insert method and retrieve method.

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();
          },


          )

Solution

  • This might not be the most efficient way of doing this, but it does the work. I have added a pull down refresher. It refreshes the contents of the page and shows it. You can find the package here- Pull Down Refresh