Flutter - How to fix `Instance of 'Future<int>'` when querying SQLite database - flutter

Since I want to test foreign key features with SQLite, I am trying to make a simple app.
The app should display inventory information like this:
I made two tables on the SQLite database and added records directly by querying on Android Studio's Database Inspector.
items table
prices table
I tried to get each item's price by querying in the app, but Instance of 'Future<int>' displayed. How can I display item prices correctly?
Main code
class SqliteForeignKeyScreen extends StatefulWidget {
const SqliteForeignKeyScreen({
Key? key,
}) : super(key: key);
#override
State<SqliteForeignKeyScreen> createState() => _SqliteForeignKeyScreenState();
}
class _SqliteForeignKeyScreenState extends State<SqliteForeignKeyScreen> {
Future<List<Item>>? _itemsList;
void _updateItemsList() {
setState(() {
_itemsList = DatabaseHelper.instance.getAllItemsList();
});
}
#override
void initState() {
super.initState();
_updateItemsList();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Items'),
),
body: FutureBuilder(
future: _itemsList,
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasError) {
Text('ERROR: ${snapshot.error}');
}
if (snapshot.hasData == false) {
return const CircularProgressIndicator();
}
if (snapshot.data.length == null || snapshot.data.length == 0) {
return const Text('no items');
}
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (_, index) {
return _buildItemCards(snapshot.data[index]);
});
},
),
);
}
_buildItemCards(Item item) {
var price = DatabaseHelper.instance.getItemPrice(item.id!);
print('item: ${item.name}, price: ${price}G');
return Card(
child: ListTile(
title: Text(item.name),
subtitle: Text('${price}G'),
),
);
}
}
database_helper.dart
class DatabaseHelper {
static final DatabaseHelper instance = DatabaseHelper._instance();
static Database? _db;
DatabaseHelper._instance();
Future<Database?> get db async {
_db ??= await _initDb();
return _db;
}
void _configureDb(Database db) async {
await db.execute('PRAGMA foreign_keys = ON;');
}
void _createDb(Database db, int version) async {
await db.execute('CREATE TABLE items('
'id INTEGER PRIMARY KEY AUTOINCREMENT,'
'name TEXT'
');');
await db.execute('CREATE TABLE prices('
'id INTEGER PRIMARY KEY AUTOINCREMENT,'
'item_id INTEGER,'
'price INTEGER,'
'FOREIGN KEY(item_id) REFERENCES items(id)'
');');
}
Future<Database> _initDb() async {
var databasePath = await getDatabasesPath();
String path = p.join(databasePath, 'inventory.db');
final inventoryDb = await openDatabase(path,
version: 1, onConfigure: _configureDb, onCreate: _createDb);
return inventoryDb;
}
Future<List<Map>> getAllItemsMapList() async {
Database? db = await this.db;
final List<Map<String, dynamic>> result = await db!.query('items');
return result;
}
Future<List<Item>> getAllItemsList() async {
final List<Map> itemsMapList = await getAllItemsMapList();
final List<Item> itemsList = [];
for (var itemMap in itemsMapList) {
itemsList.add(Item.fromMap(itemMap));
}
return itemsList;
}
Future<int> getItemPrice(int itemId) async {
final Database? db = await this.db;
final result =
await db!.query('prices', where: 'item_id = ?', whereArgs: [itemId]);
return result[0]['price'] as int;
}
}
item_model.dart
class Item {
int? id;
String name;
Item({
required this.name,
});
Item.withId({
this.id,
required this.name,
});
factory Item.fromMap(Map map) {
return Item.withId(
id: map['id'],
name: map['name'],
);
}
}
Result of print('item: ${item.name}, price: ${price}G');
item: Apple, price: Instance of 'Future<int>'G
item: Banana, price: Instance of 'Future<int>'G
item: Chocolate, price: Instance of 'Future<int>'G
When I changed _buildItemCards like this (added await and async):
_buildItemCards(Item item) async {
var price = await DatabaseHelper.instance.getItemPrice(item.id!);
print('item: ${item.name}, price: ${price}G');
return Card(
child: ListTile(
title: Text(item.name),
subtitle: Text('${price}G'),
),
);
}
The print('item: ${item.name}, price: ${price}G'); shows correctly:
item: Apple, price: 2G
item: Banana, price: 1G
item: Chocolate, price: 3G
However, the error type 'Future<dynamic>' is not a subtype of type 'Widget' occurred on the screen.

The getItemPrice is a Future function, so you should await for its result, like this:
var price = await DatabaseHelper.instance.getItemPrice(item.id!);
And also the best way to use async function in build method is using FutureBuilder, so change your _buildItemCards to this:
FutureBuilder<int>(
future: DatabaseHelper.instance.getItemPrice(item.id!),
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return Text('Loading....');
default:
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
int price = snapshot.data!;
return Card(
child: ListTile(
title: Text(item.name),
subtitle: Text('${price}G'),
),
);
}
}
},
)

Related

How to retrieve particular data from id on flutter

How to retrieve particular data from id on flutter and want to show data inside list view. I have created view, insert, delete and update operations.i used sqflite
my code is below.
main.dart file
class _SqliteAppState extends State<SqliteApp> {
int? selectedId;
final textController = TextEditingController();
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: TextField(
controller: textController,
),
),
body: Center(
child: FutureBuilder<List<Grocery>>(
future: DatabaseHelper.instance.getGroceries(),
builder: (BuildContext context,
AsyncSnapshot<List<Grocery>> snapshot) {
if (!snapshot.hasData) {
return Center(child: Text('Loading...'));
}
return snapshot.data!.isEmpty
? Center(child: Text('No Groceries in List.'))
: ListView(
children: snapshot.data!.map((grocery) {
return Center(
child: Card(
color: selectedId == grocery.id
? Colors.white70
: Colors.white,
child: ListTile(
title: Text(grocery.name),
onTap: () {
setState(() {
if (selectedId == null) {
textController.text = grocery.name;
selectedId = grocery.id;
} else {
textController.text = '';
selectedId = null;
}
});
},
onLongPress: () {
setState(() {
DatabaseHelper.instance.remove(grocery.id!);
});
},
),
),
);
}).toList(),
);
}),
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.save),
onPressed: () async {
selectedId != null
? await DatabaseHelper.instance.update(
Grocery(id: selectedId, name: textController.text),
)
: await DatabaseHelper.instance.add(
Grocery(name: textController.text),
);
setState(() {
textController.clear();
selectedId = null;
});
},
),
),
);
}
The model class code is below
Grocery({this.id, required this.name});
factory Grocery.fromMap(Map<String, dynamic> json) => new Grocery(
id: json['id'],
name: json['name'],
);
Map<String, dynamic> toMap() {
return {
'id': id,
'name': name,
}; } }
This is my db_helper class code. I have created view, insert, delete and update operations.
class DatabaseHelper {
DatabaseHelper._privateConstructor();
static final DatabaseHelper instance = DatabaseHelper._privateConstructor();
static Database? _database;
Future<Database> get database async => _database ??= await _initDatabase();
Future<Database> _initDatabase() async {
Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, 'groceries.db');
return await openDatabase(
path,
version: 1,
onCreate: _onCreate,
);
}
Future _onCreate(Database db, int version) async {
await db.execute('''
CREATE TABLE groceries(
id INTEGER PRIMARY KEY,
name TEXT
)
''');
}
Future<List<Grocery>> getGroceries() async {
Database db = await instance.database;
var groceries = await db.query('groceries', orderBy: 'name');
List<Grocery> groceryList = groceries.isNotEmpty
? groceries.map((c) => Grocery.fromMap(c)).toList()
: [];
return groceryList;
}
Future<int> add(Grocery grocery) async {
Database db = await instance.database;
return await db.insert('groceries', grocery.toMap());
}
Future<int> remove(int id) async {
Database db = await instance.database;
return await db.delete('groceries', where: 'id = ?', whereArgs: [id]);
}
Future<int> update(Grocery grocery) async {
Database db = await instance.database;
return await db.update('groceries', grocery.toMap(),
where: "id = ?", whereArgs: [grocery.id]);
}
}
You can use this function to get the data by id:
Future<List<Grocery>> getGrocerieById(int id) async {
Database db = await instance.database;
var groceries =
await db.query('groceries', where: 'id = ?', whereArgs: [id]);
List<Grocery> groceryList = groceries.isNotEmpty
? groceries.map((c) => Grocery.fromMap(c)).toList()
: [];
return groceryList;
}

getting an error type int is not a subtype of string

I creating a demo for sqlite where I have created a model class category model and in sqlite I have created some default categories in its on create method and now want to show all categories on home screen using future builder but its execute error part of feature builder..and app starts with center text
type int is not a subtype of string
category model
class CategoryModel{
String title;
IconData icon;
int entries;
double totalamount;
CategoryModel({required this.title,this.entries=0,required this.icon,this.totalamount=0.0});
Map<String,dynamic> tomap()
{
return {
'title':title,
'entries':entries,
'totalamount':totalamount.toString()
};
}
factory CategoryModel.frommap(Map<String,dynamic> map)
{
return CategoryModel(
title: map['title'],
icon: icons[map['title']]!,
entries: map['entries'],
totalamount: double.parse(map['totalamount'])
);
}
}
this is the widget where I am using futurebuilder
Widget getbody()
{
return FutureBuilder(
future: SqfliteProvider.fetchcategory(),
builder: (context,AsyncSnapshot<List<CategoryModel>?>snapshot){
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator();
} else if (snapshot.hasError) {
return Center(
child: Text(snapshot.error.toString()+' Founded'),
);
} else if (snapshot.hasData) {
if (snapshot.data != null) {
return ListView.builder(
itemCount: snapshot.data!.length,
itemBuilder: (context, index) {
CategoryModel t = snapshot.data![index];
print(t.title.toString());
print(' ');
print(t.entries.toString());
print(' ');
print(t.totalamount.toString());
return Card(
child: ListTile(
leading: CircleAvatar(
child: Icon(icons[t.title]),
),
title: Text(t.title.toString(),style: TextStyle(fontSize: 18,fontWeight: FontWeight.bold),),
subtitle:Text(
"Entries :"+t.entries.toString(),
style: TextStyle(fontSize: 14),
) ,
),
);
});
} else {
return Text('Something wrong');
}
} else {
return Text('Last if');
}
},
);
}
this is my database helper class
class SqfliteProvider {
static Future<Database> _getdb() async {
return openDatabase(join(await getDatabasesPath(), 'expensedb1.db'),
version: 1,
onCreate: (db,version) {
db.execute("CREATE TABLE categorytb(title TEXT NOT NULL,entries INTEGER NOT NULL,totalamount STRING NOT NULL)");
//add some default categories
print('I am ready to call');
for(int x=0;x<icons.length;x++)
{
db.insert('categorytb', {
'title':icons.keys.toList()[x],
'entries':0,
'totalamount':(0.0).toString()
});
}
});
}
static Future<List<CategoryModel>?> fetchcategory() async{
final db=await _getdb();
List<CategoryModel> templist=[];
List<Map<String,dynamic>> maplist=await db.query('categorytb');
print(maplist.toString());
if(maplist.isEmpty)
return null;
templist=maplist.map((e) => CategoryModel.frommap(e)).toList();
return templist;
}
}
Try to convert toString.
factory CategoryModel.frommap(Map<String, dynamic> map) {
IconData getIconData(data) {
try {
return IconData(data);
} catch (e) {
return IconData(Icons.abc.codePoint);
}
}
return CategoryModel(
title: map['title'].toString(),
icon: getIconData(map['title']), // pass different data if needed
entries: int.tryParse(map['entries'].toString()) ?? 0,
totalamount: double.tryParse(map['totalamount']) ?? 0,
);
}

How to get data from model class with using SQFlite in Flutter?

Here I use SqFlite functionality with model class for data store. But problem is that, when I click on button, addData method was called null.
This is my model class.
import 'dart:convert';
DatabaseModel fromJson({String str}) {
final jsonData = json.decode(str);
return DatabaseModel.fromMap(jsonData);
}
String toJson(DatabaseModel databaseModel) {
final dyn = databaseModel.toMap();
return json.encode(dyn);
}
class DatabaseModel {
String id;
String imageUrl;
String title;
String description;
String newsLink;
String createDate;
String category;
String footerTitle;
DatabaseModel(
{this.id,
this.imageUrl,
this.title,
this.description,
this.newsLink,
this.createDate,
this.category,
this.footerTitle});
factory DatabaseModel.fromMap(Map<String, dynamic> json) => DatabaseModel(
id: json['id'],
imageUrl: json['imageUrl'],
title: json['title'],
description: json['description'],
newsLink: json['newsLink'],
createDate: json['createDate'],
category: json['category'],
footerTitle: json['footerTitle']);
Map<String, dynamic> toMap() => {
'id': id,
'imageUrl': imageUrl,
'title': title,
'description': description,
'newsLink': newsLink,
'createDate': createDate,
'category': category,
'footerTitle': footerTitle
};
}
Now, I display my database class which I use for Add, Delete, and Get data. In this class I use Model class because I want to display my data in Bookmark class.
import 'dart:io';
import 'package:news_app/src/model/bookmark_db_provider.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
class DatabaseProvider {
// DatabaseProvider._();
// static final DatabaseProvider db = DatabaseProvider._();
Database _database;
Future<Database> get database async {
if (_database != null) return _database;
_database = await getDatabaseInstance();
return _database;
}
Future<Database> getDatabaseInstance() async {
Directory directory = await getApplicationDocumentsDirectory();
String path = join(directory.path, 'bookmark.db');
return await openDatabase(path, version: 1,
onCreate: (Database db, int version) async {
await db.execute('create table Bookmark ('
'id integer primary key autoincrement,'
'imageUrl text,'
'title text,'
'description text,'
'newsLink text,'
'createDate text,'
'category text,'
'footerTitle text'
')');
});
}
addToDatabase(DatabaseModel databaseModel) async {
final db = await database;
var raw = await db.insert('Bookmark', databaseModel.toMap(),
conflictAlgorithm: ConflictAlgorithm.replace);
return raw;
}
updateDatabase(DatabaseModel databaseModel) async {
final db = await database;
var response = await db.update('Bookmark', databaseModel.toMap(),
where: 'id = ?', whereArgs: [databaseModel.id]);
return response;
}
Future<DatabaseModel> getDatabaseModelWithId(int id) async {
final db = await database;
var response = await db.query('Bookmark', where: 'id = ?', whereArgs: [id]);
return response.isNotEmpty ? DatabaseModel.fromMap(response.first) : null;
}
Future<List<DatabaseModel>> getAllData() async {
final db = await database;
var response = await db.query('Bookmark');
List<DatabaseModel> list =
response.map((c) => DatabaseModel.fromMap(c)).toList();
return list;
}
deleteDatabase(int id) async {
final db = await database;
return db.delete('Bookmark', where: 'id = ?', whereArgs: [id]);
}
deleteAllDatabase() async {
final db = await database;
db.delete('Bookmark');
}
}
Here I display my BookMark class. This class I use for display data for user.
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:news_app/src/model/bookmark_db_provider.dart';
import 'package:news_app/src/screens/home.dart';
import 'package:news_app/src/utils/database.dart';
class BookMark extends StatefulWidget {
#override
_BookMarkState createState() => _BookMarkState();
}
class _BookMarkState extends State<BookMark> {
DatabaseProvider databaseProvider;
#override
void initState() {
super.initState();
databaseProvider = DatabaseProvider();
}
#override
void dispose() {
super.dispose();
}
#override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () => Navigator.push(
context, MaterialPageRoute(builder: (context) => HomePage())),
child: Scaffold(
backgroundColor: Theme.of(context).primaryColor,
appBar: AppBar(
backgroundColor: Theme.of(context).appBarTheme.color,
elevation: 0,
centerTitle: true,
title: Text(
'BookMark News',
style: TextStyle(fontSize: 23, fontWeight: FontWeight.bold),
),
),
body: Container(
padding: EdgeInsets.all(8.0),
child: FutureBuilder<List<DatabaseModel>>(
future: databaseProvider.getAllData(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) {
var common = snapshot.data[index];
return Card(
elevation: 5.0,
child: ListTile(
leading: SizedBox(
height: 85,
width: 79,
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(5.0),
image: DecorationImage(
image:
NetworkImage(common['imageUrl']),
fit: BoxFit.cover)),
),
),
title: Text(common['title']),
isThreeLine: true,
subtitle: Text(common['footerTitle']),
trailing: Column(
children: <Widget>[
Text(common['createDate']),
Text(common['category'])
],
),
),
);
});
} else {}
return Center(
child: CircularProgressIndicator(),
);
},
)
)),
);
}
}
I all of data in Home Page and in this Page when I pressed on button it display Method was called null. This type I handle onclick.
onPressed: () async {
print('added data');
dbHelper.addToDatabase(DatabaseModel(
imageUrl: allNewsDetail[index]['image_url'],
category: allNewsDetail[index]['category'],
footerTitle: allNewsDetail[index]['footer_title'],
createDate: allNewsDetail[index]['created_date'],
newsLink: allNewsDetail[index]['news_link'],
description: allNewsDetail[index]['description'],
title: allNewsDetail[index]['title']));
Navigator.push(context,MaterialPageRoute(builder: (context) =>BookMark()));
}
When click on button it displays this error.
The method 'getAllData' was called on null.
Receiver: null
Tried calling: getAllData()
Please check This code I give me solution for it.
You are not passing in the databaseProvider into this class and that is why you are getting null!

How to add data to an existing document in firestore - Flutter

I am using Firebase Database to store information regarding my flutter app.
I have manually updated my collections and documents.
But in one instance I want my users to setdata in my documents so it gets reflected in the app for that particular user. But, when the user does setdate it goes and creates new documents which I do not want, I want the user to setdata in the existing document. I did try but no luck.
Here are my codes:
class FirestoreService {
FirestoreService._();
static final instance = FirestoreService._();
Future<void> setData(
{#required String path, Map<String, dynamic> data}) async {
final reference = Firestore.instance.document(path);
await reference.setData(data);
}
abstract class Database {
Future<void> setRackBook(RackBookItems rackBookItems);
}
bool documentCheckBox() => true;
class FirestoreDatabase implements Database {
final String uid;
FirestoreDatabase({#required this.uid}) : assert(uid != null);
final _service = FirestoreService.instance;
#override
Future<void> setRackBook(RackBookItems rackBookItems) async =>
await _service.setData(
path: APIPath.rackBookItems(uid, rackBookItems.id),
data: rackBookItems.toMap());
}
class PageScreen extends StatefulWidget {
final RackBookItems rackBookItems;
final Database database;
const PageScreen(this.rackBookItems, {#required this.database});
static Future<void> show(
BuildContext context, {
Database database,
RackBookItems rackBookItems,
}) async {
final database = Provider.of<Database>(context);
await Navigator.of(context, rootNavigator: true).push(
MaterialPageRoute(
fullscreenDialog: false,
builder: (context) => PageScreen(
rackBookItems,
database: database,
),
),
);
}
#override
_PageScreenState createState() => _PageScreenState();
}
class _PageScreenState extends State<PageScreen> {
final _formKey = GlobalKey<FormState>();
bool _validateAndSaveForm() {
final form = _formKey.currentState;
if (form.validate()) {
form.save();
return true;
}
return false;
}
Future<void> _completed() async {
if (_validateAndSaveForm()) {
try{
final checkBox = widget.rackBookItems?.checkBox ?? documentCheckBox();
final rackBookItems = RackBookItems(checkBox: checkBox);
await widget.database.setRackBook(rackBookItems);
Navigator.of(context).pop();
} on PlatformException catch (e) {
PlatformExceptionAlertDialog(
title: 'Operations failed',
exception: e,
).show(context);
}
}
}
#override
Widget build(BuildContext context) {
final auth = Provider.of<AuthBase>(context, listen: true);
return SafeArea(
child: Scaffold(
body: Column(
children: <Widget>[
StreamBuilder<User>(
stream: auth.onAuthStateChange,
builder: (context, snapshot) {
User user = snapshot.data;
if (snapshot.hasData) {
return Provider<Database>(
create: (_) => FirestoreDatabase(uid: user.uid),
child: Text('Data'),
);[![enter image description here][1]][1]
}
return Center(
child: CircularProgressIndicator(),
);
},
),
Form(
key: _formKey,
child: RaisedButton(
child: Text(
'Done',
style: TextStyle(color: Theme.of(context).accentColor),
),
onPressed: _completed,
),
)
],
),
),
);
}
}
class RackBookItems {
final String id;
final String rackId;
final String title;
final bool checkBox;
const RackBookItems({
this.id,
this.rackId,
this.title,
this.checkBox,
});
Map<String, dynamic> toMap() {
return {
'checkBox': checkBox,
};
}
factory RackBookItems.fromMap(Map<String, dynamic> data, String id) {
if (data == null) {
return null;
}
final String id = data['id'];
final String rackId = data['rackId'];
final String title = data['title'];
final bool checkBox = data['checkBox'];
return RackBookItems(
id: id,
rackId: rackId,
title: title,
checkBox: checkBox,
);
}
}
This is how my firebase looks like.
[1]: https://i.stack.imgur.com/Z07ai.png
Is there any error with the path I have given?
class APIPath {
static String rackBookItems( String uid, String id) =>
'rackBookItems/$id/';
}
You need to use updateData, this method required you to know the document's Document ID
Firestore.instance.collection('rackBookItems').document('book1').updateData({
'newData' : 14
});
If you need to update all of your documents, you can pull all of the documents and use a for loop to update them.
QuerySnapshot qs = await Firestore.instance.collection('rackBookItems').getDocuments();
List<DocumentSnapshot> books = qs.documents;
for (int i = 0; i < books.length; i++){
Firestore.instance.collection('rackBookItems').documents(books[i].documentID).updateData({
'title' : newData
});
}
updateData is good but in case the document does not exist you should use setData and set merge: true
class FirestoreService {
FirestoreService._();
static final instance = FirestoreService._();
Future<void> setData(
{#required String path, Map<String, dynamic> data}) async {
final reference = Firestore.instance.document(path);
await reference.setData(data, merge:true);
}

type 'Future<dynamic>' is not a subtype of type 'List<Profile>

class Profile {
final List<String> photos;
final String name;
final int age;
final String education;
final String bio;
final int distance;
Profile({
this.photos,
this.name,
this.age,
this.education,
this.bio,
this.distance
});
}
class _MainControllerState extends State<MainController> {
static List<Profile> demoProfiles = fetchData();
static fetchData() async{
final db = await Firestore.instance;
List<Profile> list = [];
db.collection("users").getDocuments().then((querySnapshot){
querySnapshot.documents.forEach((document) {
list.add(Profile(
photos: document['photoUrl'],
name: document['photoUrl'],
age: document['photoUrl'],
distance: document['photoUrl'],
education: document['photoUrl']
));
});
});
return list;
}
final MatchEngine matchEngine = MatchEngine (
matches:demoProfiles.map((Profile profile) => Match(profile:
profile)).toList()
);
I am new to flutter.
when I run my code , I got the error :type 'Future' is not a subtype of type 'List .and if I change screen I will get the error:NoSuchMethodError: The method 'map' was called on null. How can I solve it ?
Thank you for helping me .
You need to specify the return type of method fetchData
static Future<List<Profile>> fetchData() async{
You need to convert you method to getData
Future<List<Data>> getData() async {
var response =
await http.get(Uri.https('jsonplaceholder.typicode.com', 'users'));
var jsonData = jsonDecode(response.body);
List<Data> dataList = [];
for (var u in jsonData) {
Data data = Data(u["name"], u["phone"], u["email"]);
dataList.add(data);
}
print(dataList.length);
return dataList;
}
And display in a Card
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Data Fetch"),
),
body: Container(
child: Card(
child: FutureBuilder<List<Data>>(
future: getData(),
builder: (context, snapshot) {
if (snapshot.data == null) {
return Container(
child: Text("Loading"),
);
}else{
return ListView.builder(
itemCount: snapshot.data!.length,
itemBuilder: (context, i) {
return ListTile(
title: Column(
children: [
Text(snapshot.data![i].name),
Text(snapshot.data![i].phone),
Text(snapshot.data![i].email),
],
),
);
});
}
},
),
),
));
}
Its worked for me :) :) I hope this will help you.