Search code examples
fluttermobile-developmentflutter-futurebuilder

Unable to update FutureBuilder after inserting data in sqlite (Flutter)


I am new to Flutter development and I am trying to create a simple application.

In my application there are 3 widgets:

First Widget is like home screen which has Bottom Navigation and a Floating Action Button.

On first Tab of BottomNavigation I am loading Widget2 which is just simple list with FutureBuilder.

On click of FloatingActionButton I am staring Widget3, which is kind of form to add data in Sqlite. After inserting data to Sqlite it come back to Widget2.

In Widge2, List is not getting updated with new inserted data.

Code of Widget2:

class Goals extends StatefulWidget {
  const Goals({Key? key}) : super(key: key);

  @override
  State<Goals> createState() => _GoalsState();
}

class _GoalsState extends State<Goals> {
  late List<Goal> goals;
  late var futureData;

  @override
  Widget build(BuildContext context) {
    futureData = getAllGoals();
    return FutureBuilder(
      future: futureData,
      builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
        if (snapshot.hasData) {
          goals = snapshot.data as List<Goal>;
          if (goals.isEmpty) {
            return const Center(
              child: Text(
                "No Goals added yet",
                style: TextStyle(
                  fontSize: 20.0,
                  fontWeight: FontWeight.bold,
                  fontFamily: "JosefinSans",
                ),
              ),
            );
          }
          return Scaffold(
            body: Padding(
              padding: const EdgeInsets.all(16.0),
              child: SingleChildScrollView(
                child: //My UI,
                ),
              ),
            ),
          );
        }else{
          return const Text("No Goals added yet");
        }
      },
    );
  }

I hope this information is enought, Please let me know if more information needed. I am not sure it is possible with futureBuilder or not, if not please suggest me Alternative widget.

Thanks in advance.

I tried lot of things proposed by experts on stackoverflow but nothing seems to work for me.


Solution

  • I resolved the issue by using ValueListableBuilder.

    FutureBuilder should be used only in case where you do not want to get updated data.