FLUTTER+SQL: display Data from Database in ListViewBuilder

Viewed 77

Im using MS SQL and I want to read data and display it in a ListViewBuilder, but Im having some difficulties.

I dont know how to find itemCount (biggest problem)

I dont know how to display Data in ListTile

query - "SELECT * FROM TabelTest"

Below I will show a part of code and how I want to be shown in app:

// This is to get and display in terminal data from db
    Future<void> read(String query) async {
        var res = await SqlConn.readData(query);
        debugPrint(res.toString());
      }

Data that I need to put in ListTile data shown in terminal

This is how I want to show data (Red underlines are main problem) enter image description here

2 Answers

try this:

FutureBuilder<List?>(
        future: read("SELECT * FROM TabelTest"),
        builder: (context, snapshot) {
          switch (snapshot.connectionState) {
            case ConnectionState.waiting:
              return Text('Loading....');
            default:
              if (snapshot.hasError)
                return Text('Error: ${snapshot.error}');
              else
                List data = snapshot.data ?? [];
                return ListView.builder(
                    itemCount: data.length,
                    itemBuilder: (context, index) {
                      return Text((data[index] as Map)['name']);
                    });
          }
        })

also change this:

Future<List?> read(String query) async {
     final result = await SqlConn.readData(query);
     return jsonDecode(result) as List;
}

First at all, I would recommend you to map the data into a model, its considered a good practice and avoid possible type casting related bugs.

Second, you could use a FutureBuilder to make the asynchronous call to the SQL database. I also would modify your read method to return to retrieved data of the database and work together with FutureBuilder.

Related