Flutter: Check local image if exist - flutter

Following the last answer here, i am getting error
error: The element type 'Future' can't be assigned to the list type 'Widget'.
Future<Widget> getImage(String path) async {
try {
await rootBundle.load(path);
return Image.asset(path);
} catch (_) {
return SizedBox.shrink();
}
}
My code looks like this:
child: Column(
children: <Widget>[
Text('Text 1'),
Text('Show below image if exist'),
getImage('fileName'),
],
How to use 'getImage' to return the desired Widget?

Try Future Builder, i.e :
child: Column(
children: <Widget>[
Text('Text 1'),
Text('Show below image if exist'),
FutureBuilder(
future: getImage("filename"),
builder: (BuildContext context, AsyncSnapshot<Widget> snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
return snapshot.data!;
} else {
return SizedBox.shrink();
}
},
),
],

Related

Flutter : Instance of Future<dynamic>

I am trying to print a value returned from a function to the screen.
Function:
calculation.dart:
Future<dynamic> getTotalCost(BuildContext context) async {
final user = Provider.of<Userr?>(context, listen: false);
double totalCost = 0.0;
QuerySnapshot snapshot = await FirebaseFirestore.instance
.collection('myOrders')
.doc(user?.uid)
.collection('items')
.get();
for (var doc in snapshot.docs) {
totalCost += doc["price"];
}
print(totalCost.toString());
return totalCost.toString();
}
But instead printing the value , it prints Instance of Future.
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text('Item total', style: textStyle),
Text('${ Provider.of<Calculations>(context, listen: false).getTotalCost(context).toString()}', style: textStyle),
],
),
I also know the reason that this is due to the function is asynchronous, it returns future object instead of actual value. But I need to know how can I change the above code in order to print the actual value.
Try the following code:
FutureBuilder(
future: Provider.of<Calculations>(context, listen: false).getTotalCost(context),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text('Item total', style: textStyle),
Text('${snapshot.data}', style: textStyle),
],
);
} else if (snapshot.hasError) {
return Text("Error: ${snapshot.error.toString()}");
} else {
return const CircularProgressIndicator();
}
},
),
In order to reduce the number of Widget rebuild, and for performance optimization, I suggest to only wrap the Widget to update with the Future value.
By doing so, you limit the Widget tree in the builder of the FutureBuilder to the strict necessary.
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text('Item total', style: textStyle),
FutureBuilder(
future: Provider.of<Calculations>(context, listen: false)
.getTotalCost(context),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text('${snapshot.data}', style: textStyle);
} else if (snapshot.hasError) {
return Text("Error: ${snapshot.error.toString()}");
} else {
return const CircularProgressIndicator();
}
},
),
],
),

The argument type 'Iterable<dynamic>' can't be assigned to the parameter type 'List<Gif>'

I was trying to use the Giphy API to start using APIs in flutter but I got this bug and I don’t know how to fix it.
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: FutureBuilder<Iterable>(
future: _listadoGifs,
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView(
children: _listGifs(snapshot.data!),
);
} else if (snapshot.hasError) {
return Text("error");
}
return Center(
child: CircularProgressIndicator(),
);
},
),
);
}
I do not use a List because I use the following class:
List<Widget> _listGifs(List<Gif> data) {
List<Widget> gifs = [];
for (var gif in data) {
gifs.add(Card(
child: Column(
children: [
Image.network(gif.url.toString()),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(gif.name.toString()),
),
],
)));
}
return gifs;
}

FutureBuilder has empty snapshot despite Future returns proper data

I have FutureBuilder widget as Scaffold's body and I want to display a list of widgets when database returns required info but while database is properly returning data the FutureBuilder does not show any widgets(like CircularProgressIndicator or required List as it finishes its job). Code shown below:
Future<List<Widget>> getList() async{
List<Widget> list = [];
var db = dbMethods();
db.getConnection().then((conn) async {
await Future.delayed(const Duration(seconds: 1));
var result = await conn.query("select * from info", []);
for(var row in result) {
var item = BilbordItem(
firm: row[2],
constructionType: row[3],
demonstrationType: row[4],
lat: double.parse(row[5]),
long: double.parse(row[6]),
sizeX: double.parse(row[7]),
sizeY: double.parse(row[8]),
address: row[9],
positionRate: int.parse(row[10]),
colorsRate: int.parse(row[11]),
passabilityRate: int.parse(row[12]),
typeRate: int.parse(row[13])
);
print(item.address); //here i was checking if database fetch is working and it does print required info
list.add(item);
}
conn.close();
});
return list;
}
class _ListPage extends State<ListPage>{
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Список билбордов"),
centerTitle: true,
),
body: FutureBuilder(
future: getList(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if(snapshot.connectionState == ConnectionState.done){
if(snapshot.hasData && !snapshot.hasError){
return Center(
child: Column(
children: snapshot.data,
),
);
}
else if(snapshot.hasError){
return SingleChildScrollView(
child: Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const Icon(Icons.error_outline, color: Colors.red,),
Text(snapshot.error.toString()),
],
),
),
);
}
}else {
return Center(child: CircularProgressIndicator());
}
return Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: const [
Text("Empty"),
],
),
);
},
),
);
}
}

UnimplementedError error in FutureBuilder while displaying inserted data from database

I'm trying to create a Futurebuilder function to call and display all data that inserted in database unfortunately I got this error 'UnimplementedError' and im pretty stock on this any suggestion will be appreciated.
Here in my full code for implementation to display data in been trying to fix my error 'UnimplementedError' in which I'm trying to do is to display inserted in list view not in web view any suggestion will be appreciated.
body: Center(
child: Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
FutureBuilder<ContactsDao>(
future: _calltheStream(),
builder: (BuildContext context,
AsyncSnapshot<ContactsDao> snapshot) {
if (!snapshot.hasData ||
snapshot.connectionState == ConnectionState.none) {
return Container(
child: CircularProgressIndicator(),
);
} else {
return StreamBuilder<List<ContactObject>>(
stream: snapshot.data.findallContactsById(),
builder: (context, snapshot) {
if (!snapshot.hasData ||
snapshot.connectionState ==
ConnectionState.none) {
return Container(
child: CircularProgressIndicator(),
);
} else {
if(widget.Contactlist.length != snapshot.data.length){
widget.Contactlist = snapshot.data;
}
if(snapshot.data.length == 0){
return Center(
child: Text('No Data Found'),
);
}
return Expanded(
child: ListView.builder(
scrollDirection: Axis.vertical,
itemCount: snapshot.data.length,
itemBuilder:
(BuildContext context, int index) {
return Card(
child: ListTile(
leading: Checkbox(
value: widget.Contactlist[index].isSelect,
onChanged: (bool value) {
setState(() {
widget.Contactlist[index].isSelect = value;
});
},
),
trailing: GestureDetector(
onTap: () {
_selectedDetele(snapshot.data[index].id);
},
child: Icon(Icons.delete),
),
title: Text('${snapshot.data[index].task}',maxLines: 1,),
subtitle: Text('${snapshot.data[index].time}',style: TextStyle(fontSize: 10),),
));
}),
);
}
}); //DATA
} //DATA
}), // DATA
], // DATA
), // DATA
),//DATA
),
Future<ContactsDao> _calltheStream() async { //GET ALL DATA HERE
ContactDatabase contactDatabase = await widget.database;
widget._contactsdao = contactDatabase.contactsDao;
return contactDatabase.contactsDao;
}

SearchDelegate With Http

I try to using searchdelgit with future list from JSON, when. But I got
this error:
formatException :Unexpected character (at line 2 , character1)
altho I already use the same code without search page and it works perfectly
any idea guys
#override
Widget buildResults(BuildContext context) {
// show some result based on the selection
if (query.length < 3) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Center(
child: Text(
"Search term must be longer than two letters.",
),
)
],
);
}
return FutureBuilder(
future: _fetchProductSearch(query),
builder: (context, AsyncSnapshot<List<Products>> snapshot) {
if (!snapshot.hasData) {
return Text(snapshot.error.toString());
} else if (snapshot.data.length == 0) {
return Column(
children: <Widget>[
Text(
"No Results Found.",
),
],
);
} else {
var results = snapshot.data;
return ListView.builder(
itemCount: results.length,
itemBuilder: (context, index) {
var result = results[index];
return ListTile(
title: Text(result.artitle),
);
},
);
}
},
);
}
formatException :Unexpected character (at line 2 , character1)