Edoardo Tavilla
Edoardo Tavilla

Reputation: 563

Retrieve data stored in SQFlite database (Flutter)?

I have a model class Pet used toMap and fromMap:

  Map<String, dynamic> toMap() {
return {
  'id': id,
  'image': image,
  'name': name,
  'birth': birth,
  'colour': colour,
  'breed': breed,
  'hairlength': hairLength,
  'sterilized': sterilized,
  'vaccinated': vaccinated
   };
  }

    Pet.fromMap(Map<String, dynamic> map) {
    id = map['id'];
    image = map['image'];
    name = map['name'];
    birth = map['birth'];
    breed = map['breed'];
    colour = map['colour'];
    hairLength = map['hairlength'];
    sterilized = map['sterilized'];
    vaccinated = map['vaccinated'];
  }

I store all in my database and I want to retrieve images (stored as strings) so I used this method:

  Future<List<String>> getImages() async {
    var dbClient = await db;
    List<Map> maps = await dbClient.rawQuery("SELECT * FROM $TABLE");
    List<String> images = [];
    if (maps.length > 0) {
       for (int i = 0; i < maps.length; i++) {
           images.add(Pet.fromMap(maps[i]).image);
      }
     }
    return images;
  }

How can I use Future<List<String>> to read each String associated to each image?

Upvotes: 1

Views: 2228

Answers (2)

WaQar HuSsain
WaQar HuSsain

Reputation: 61

You can use in this way

 body: new Container(
    padding: new EdgeInsets.all(10.0),
    child: new FutureBuilder<List<Teams>>(
      future: fetchTeamListFromDatabase(),
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          return new ListView.builder(
              itemCount: snapshot.data.length,
              itemBuilder: (context, index) {
                decoImage = snapshot.data[index].teamFlag;
                _bytesImage = Base64Decoder().convert(decoImage);

          
               
                    child: Card(

                       elevation: 2.0,
                      clipBehavior: Clip.antiAliasWithSaveLayer,
                      semanticContainer: false,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(5.0),
                      ),
                      
                      margin: EdgeInsets.all(5),
                      color: Colors.white,
                    child: ListTile(
                    //  child: Row(children: <Widget>[
                       leading: CircleAvatar(
                         radius: 26,
                          backgroundColor: Colors.white,
                      child:  ClipOval(
                          child: _bytesImage == null
                              ? new Text('No image value.')
                              : Image.memory(
                                  _bytesImage,
                                  width: 60,
                                  height: 60,
                                  fit: BoxFit.cover,
                                ),
                        ),
                       ),
                       
                     
                     // ]
                      ),
                    ),
                //  ),
                );
              });
        } else if (snapshot.hasError) {
          return new Text("No teams available yet");
        }
        return new Container(
          alignment: AlignmentDirectional.center,
          child: new CircularProgressIndicator(),
        );
      },
    ),
  ),

Upvotes: 0

Marius Schmack
Marius Schmack

Reputation: 171

Question is a tad vague, assuming like the comment mentioned that you want to use the function directly in your widget you can use a FutureBuilder or call the function in the initstate and setState after completion.

FutureBuilder version

class TextFutureWidget extends StatelessWidget {
  Future<List<String>> testFunction() async {
    return List<String>();
  }

  @override
  Widget build(BuildContext context) {
    final imagesFuture = testFunction();
    return Container(
        child: FutureBuilder(
      future: imagesFuture,
      builder: (context, snapshot) {
        if (!snapshot.hasData || snapshot.data == null) return Container();
        return Column(
          children: <Widget>[
            for (var item in snapshot.data) Text(item),
          ],
        );
      },
    ));
  }
}

Initstate version

class TestWidget extends StatefulWidget {
  @override
  _TestWidgetState createState() => _TestWidgetState();
}

class _TestWidgetState extends State<TestWidget> {
  List<String> _images;
  List<String> get images => _images;
  set images(List<String> images) {
    if (mounted) setState(() => _images = images);
  }

  @override
  void initState() {
    super.initState();
    testFunction().then((value) => images = value);
  }

  Future<List<String>> testFunction() async {
    return List<String>();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        if(images != null)
          for (var item in images)
            Text(item),
      ],
    );
  }
}

Upvotes: 1

Related Questions