RefreshIndicator not working on FutureBuilder? - flutter

Here's my full code
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import 'package:weathercheck/Weather.dart';
import 'dart:convert';
Here's where i connect my WeatherData Class
Future<WeatherData> fetchWeatherdetail() async {
final response =
await http.get('http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907d289e10d714a6e88b30761fae22');
if (response.statusCode == 200) {
// If server returns an OK response, parse the JSON.
return WeatherData.fromJson(json.decode(response.body));
} else {
// If that response was not OK, throw an error.
throw Exception('Failed to load post');
}
}
void main(){
runApp(MaterialApp(
initialRoute: '/',
routes: {
'/' : (context) => MyHome(),
'/weatherResult' : (context) => WeatherResult1()
}
)
);
}
Widget myAppBar(String txtTitle){
return AppBar(
title: Text(txtTitle),
backgroundColor: Colors.orange[300],
);
}
class MyHome extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: myAppBar('Find your city weather'),
body: Column(children:[
TextField(
onChanged: (text){
},
),
RaisedButton(
child: Text('Search'),
onPressed: (){
Navigator.pushNamed(context, '/weatherResult');
},
),
],)
);
}
}
class _WeatherResult1State extends State<WeatherResult1>{
final GlobalKey<RefreshIndicatorState> _refreshIndicatorKey =
new GlobalKey<RefreshIndicatorState>();
Future<WeatherData> weatherData;
#override
void initState() {
super.initState();
weatherData = fetchWeatherdetail();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: myAppBar('Find your city weather'),
body:
From here want to refresh but not working
RefreshIndicator(
key: _refreshIndicatorKey,
onRefresh: _refresh,
child:
FutureBuilder<WeatherData>(
future: fetchWeatherdetail(),
builder: (context, snapshot) {
if (snapshot.hasData) {
for(var i = 0; i< snapshot.data.weather.length ; i++){
return Container(
decoration: BoxDecoration(
color: Colors.transparent,
image: DecorationImage(
image: AssetImage('assets/images/london.jpg'),
fit: BoxFit.fill
)
),
child:Row(
children:<Widget>[
Column(
children: <Widget>[
Text('City ID: ', style: TextStyle(fontSize: 20,),),
Text('City Name: ', style: TextStyle(fontSize: 20),),
Text('Weather condition: ', style: TextStyle(fontSize: 20),),
Text('Weather description: ', style: TextStyle(fontSize: 20),)
],),
Column(children: <Widget>[
Text(snapshot.data.id.toString(), style: TextStyle(fontSize: 20),),
Text(snapshot.data.name, style: TextStyle(fontSize: 20),),
Text(snapshot.data.weather[i].main, style: TextStyle(fontSize: 20),),
Text(snapshot.data.weather[i].description, style: TextStyle(fontSize: 20), )
],),
]));
}
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
// By default, show a loading spinner.
return Center(
child: CircularProgressIndicator()
);
},
)
)
);
}
Here's my _refresh function
Future<Null> _refresh() async{
await Future.delayed(Duration(seconds: 2));
setState(() {
weatherData = fetchWeatherdetail();
}
);
return null;
}
}
i dont know what makes this code not working, is it refreshIndicator not working with Future builder? or something else.. im really stucking here.. and also why this stackoverflow so hard to make thread ah..

It looks that you should be using a ListView to show all your wheater items in your list. Replace the following code
for(var i = 0; i< snapshot.data.weather.length ; i++){
return Container(
decoration: BoxDecoration(
...
with
return ListView.builder(
physics: AlwaysScrollableScrollPhysics(),
itemBuilder: (context, i){
WeatherData weatherItem = snapshot.data.weather[i];
return Container(
decoration: BoxDecoration(
...
},
itemCount: snapshot.data.weather.length,
);

Related

Flutter Web Unexpected Null Value

enter image description here I get Unexpected Null value error when switching from Home page to Vehicle Add page. I couldn't understand what caused this.
I tried to run it in debug mode, but it was very confusing in debug mode, I couldn't understand it.
home.dart page
import 'package:Car_Price_App/Pages/category_add.dart';
import 'package:Car_Price_App/Pages/vehicle_add.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import '../services/auth_service.dart';
class Home extends StatefulWidget {
const Home({super.key});
#override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
#override
Widget build(BuildContext context) {
final user = FirebaseAuth.instance.currentUser;
final email = user?.email;
return Scaffold(
appBar: AppBar(
title: Center(child: Text("Sıfır Araçlar ${email?.toUpperCase()}")),
leading: const Icon(Icons.car_rental),
actions: [
IconButton(onPressed: () {
Navigator.push(context, MaterialPageRoute(builder: (context)=> CategoryAdd(gelenEmail: email.toString(),)));
print("giden $email");
}, icon: const Icon(Icons.category)),
IconButton(onPressed: () {
Navigator.push(context, MaterialPageRoute(builder: (context)=> VehicleAdd()));
}, icon: const Icon(Icons.add)),
IconButton(onPressed: () {}, icon: const Icon(Icons.update)),
IconButton(onPressed: () {}, icon: const Icon(Icons.delete)),
],
),
body: Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("Giriş Yapıldı $email"),
const SizedBox(height: 10,),
ElevatedButton(onPressed: (){
AuthService().signOut();
}, child: const Text("Çıkış Yap",),),
],
),
),
);
}
}
vehicle_add.dart page
import 'dart:io';
import 'dart:math';
import 'dart:core';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:currency_text_input_formatter/currency_text_input_formatter.dart';
import 'package:file_picker/file_picker.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../models/trade_mark_model.dart';
import '../models/type_of_vehicle_model.dart';
import '../models/vehicle_body_type_model.dart';
import '../models/vehicle_model.dart';
import '../models/vehicle_year_model.dart';
class VehicleAdd extends StatefulWidget {
const VehicleAdd({Key? key}) : super(key: key);
#override
State<VehicleAdd> createState() => _VehicleAddState();
}
class _VehicleAddState extends State<VehicleAdd> {
GlobalKey? aracEkleKey = GlobalKey<FormState>();
var db = FirebaseFirestore.instance;
TextEditingController vehicleProperties = TextEditingController();
TextEditingController vehiclePrice = TextEditingController();
String? vasitaTipi = "";
String? kasaTipi = "";
String? marka = "";
String? model = "";
String? yil = "";
PlatformFile? pickedFile;
UploadTask? uploadTask;
Future selectFile() async {
final result = await FilePicker.platform.pickFiles();
if (result == null) return;
setState(() {
pickedFile = result.files.first;
});
}
Future uploadFile() async {
final path = 'aracResimleri/${pickedFile?.name}';
final file = File(pickedFile!.path!);
final ref = FirebaseStorage.instance.ref().child(path);
setState(() {
uploadTask = ref.putFile(file);
});
final snapshot = await uploadTask?.whenComplete(() {});
final urlDownload = await snapshot?.ref.getDownloadURL();
print('Download Link : $urlDownload');
setState(() {
uploadTask = null;
});
}
Stream<List<TypeOfVehicleModel>> readVehicleType() => db.collection("Vasıtalar").snapshots().map((snapshot) => snapshot.docs.map((doc) => TypeOfVehicleModel.fromJson(doc.data())).toList());
Stream<List<VehicleBodyTypeModel>> readBodyType() => db.collection("KasaTipleri").snapshots().map((snapshot) => snapshot.docs.map((doc) => VehicleBodyTypeModel.fromJson(doc.data())).toList());
Stream<List<TradeMarkModel>> readTradeMark() => db.collection("Markalar").snapshots().map((snapshot) => snapshot.docs.map((doc) => TradeMarkModel.fromJson(doc.data())).toList());
Stream<List<VehicleModel>> readVehicleModel() => db.collection("Modeller").snapshots().map((snapshot) => snapshot.docs.map((doc) => VehicleModel.fromJson(doc.data())).toList());
Stream<List<VehicleYearModel>> readVehicleYear() => db.collection("Yıllar").snapshots().map((snapshot) => snapshot.docs.map((doc) => VehicleYearModel.fromJson(doc.data())).toList());
late int _key;
_collapse() {
int? newKey;
do {
_key = Random().nextInt(10000);
} while (newKey == _key);
}
#override
void initState() {
super.initState();
_collapse();
}
#override
Widget build(BuildContext context) {
var screenInfo = MediaQuery.of(context);
final double screenWidth = screenInfo.size.width;
final double screenHeight = screenInfo.size.height;
return Scaffold(
appBar: AppBar(
title: const Text("Araç Ekle"),
),
body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 30, vertical: 20),
child: Center(
child: Form(
autovalidateMode: AutovalidateMode.onUserInteraction,
key: aracEkleKey,
child: SizedBox(
width: screenWidth / 2,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
FutureBuilder<List<TypeOfVehicleModel>>(
future: readVehicleType().first,
builder: (context, snapshot) {
if (snapshot.hasError) {
return const Text("Something went wrong");
} else if (snapshot.hasData) {
final typeOfVehicle = snapshot.data!;
return ExpansionTile(
key: Key(_key.toString()),
initiallyExpanded: false,
leading: const Icon(Icons.merge_type),
title: const Text("Vasıta Seçiniz"),
children: typeOfVehicle.map(buildTov).toList(),
);
} else {
return const Center(
child: Padding(
padding: EdgeInsets.all(8.0),
child: CircularProgressIndicator(),
),
);
}
},
), // Vasıta Tipi
Text("$vasitaTipi"),
Text("$kasaTipi"),
Text("$marka"),
Text("$model"),
Text("$yil"),
FutureBuilder<List<VehicleBodyTypeModel>>(
future: readBodyType().first,
builder: (context, snapshot) {
if (snapshot.hasError) {
return const Text("Something went wrong");
} else if (snapshot.hasData) {
final bodyType = snapshot.data!;
return ExpansionTile(
key: Key(_key.toString()),
initiallyExpanded: false,
leading: const Icon(Icons.type_specimen),
title: const Text("Kasa Tipi Seçiniz"),
children: bodyType.map(buildBodyType).toList(),
);
} else {
return const Center(
child: Padding(
padding: EdgeInsets.all(8.0),
child: CircularProgressIndicator(),
),
);
}
},
), // Kasatipi
FutureBuilder<List<TradeMarkModel>>(
future: readTradeMark().first,
builder: (context, snapshot) {
if (snapshot.hasError) {
return const Text("Something went wrong");
} else if (snapshot.hasData) {
final tradeMarka = snapshot.data!;
return ExpansionTile(
key: Key(_key.toString()),
initiallyExpanded: false,
leading: const Icon(Icons.branding_watermark),
title: const Text("Marka Seçiniz"),
children: tradeMarka.map(buildTradeMark).toList(),
);
} else {
return const Center(
child: Padding(
padding: EdgeInsets.all(8.0),
child: CircularProgressIndicator(),
),
);
}
},
), //Markalar
FutureBuilder<List<VehicleModel>>(
future: readVehicleModel().first,
builder: (context, snapshot) {
if (snapshot.hasError) {
return const Text("Something went wrong");
} else if (snapshot.hasData) {
final model = snapshot.data!;
return ExpansionTile(
key: Key(_key.toString()),
initiallyExpanded: false,
leading: const Icon(Icons.time_to_leave),
title: const Text("Model Seçiniz"),
children: model.map(buildModel).toList(),
);
} else {
return const Center(
child: Padding(
padding: EdgeInsets.all(8.0),
child: CircularProgressIndicator(),
),
);
}
},
), //Modeller
FutureBuilder<List<VehicleYearModel>>(
future: readVehicleYear().first,
builder: (context, snapshot) {
if (snapshot.hasError) {
return const Text("Something went wrong");
} else if (snapshot.hasData) {
final year = snapshot.data!;
return ExpansionTile(
key: Key(_key.toString()),
initiallyExpanded: false,
leading: const Icon(Icons.calendar_month),
title: const Text(
"Yıl Seçiniz",
),
children: year.map(buildYear).toList(),
);
} else {
return const Center(
child: Padding(
padding: EdgeInsets.all(8.0),
child: CircularProgressIndicator(),
),
);
}
},
), //Yıllar
Padding(
padding: const EdgeInsets.all(8.0),
child: TextFormField(
controller: vehicleProperties,
decoration: const InputDecoration(
labelText: "Araç Özellikleri Giriniz",
suffixText: "Araç Özellikleri Giriniz",
border: OutlineInputBorder(),
),
minLines: 1,
maxLines: screenHeight.toInt(),
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: TextFormField(
keyboardType: TextInputType.number,
inputFormatters: <TextInputFormatter>[
// for below version 2 use this
FilteringTextInputFormatter.allow(RegExp(
r'\d',
)),
FilteringTextInputFormatter.digitsOnly,
CurrencyTextInputFormatter(
symbol: '₺',
name: "TL",
)
],
controller: vehiclePrice,
decoration: const InputDecoration(
labelText: "Araç Fiyat Giriniz",
suffixText: "Araç Fiyat Giriniz",
border: OutlineInputBorder(),
),
minLines: 1,
maxLines: screenHeight.toInt(),
),
),
Expanded(
child: Image.file(
File(pickedFile!.path!),
width: double.infinity,
fit: BoxFit.cover,
),
),
ElevatedButton.icon(
icon: const Icon(Icons.image),
onPressed: () {
selectFile();
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text("Araç Resmi Seç"),
content: Text(pickedFile!.name),
actions: [
TextButton(
onPressed: () async {
uploadFile();
},
child: const Center(
child: Text(
"Galeri'den Seç",
style: TextStyle(color: Colors.black, fontSize: 20),
))),
],
);
});
},
label: const Text("Araç Resimi Ekle"),
),
const SizedBox(
height: 30,
),
StreamBuilder<TaskSnapshot>(
stream: uploadTask!.snapshotEvents,
builder: (context, snapshot) {
if (snapshot.hasData) {
final data = snapshot.data!;
double progress = data.bytesTransferred / data.totalBytes;
return SizedBox(
height: 50,
child: Stack(
fit: StackFit.expand,
children: [
LinearProgressIndicator(
value: progress,
color: Colors.green,
backgroundColor: Colors.grey,
),
Center(
child: Text(
'${(100 * progress).roundToDouble()} %',
style: const TextStyle(color: Colors.white),
),
)
],
),
);
} else {
return const SizedBox(
height: 50,
);
}
},
)
],
),
),
),
),
),
),
// Fab Buton visible olacak doldurulması geren herşey dolduğunda gözükecek
floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
floatingActionButton: FloatingActionButton(
child: const Icon(Icons.add),
onPressed: () {
// bool kontrolSonucu = aracEkleKey.currentState!.validate();
},
),
);
}
Widget buildTov(TypeOfVehicleModel typeOfVehicleModel) => ListTile(
onTap: () {
setState(() {
_collapse();
vasitaTipi = typeOfVehicleModel.typeOfVehicle;
});
if (kDebugMode) {
print("$vasitaTipi");
}
},
leading: const Icon(
Icons.stars_outlined,
size: 10,
),
title: Text(typeOfVehicleModel.typeOfVehicle.toString()),
); //Araç vasıta tipi
Widget buildBodyType(VehicleBodyTypeModel vehicleBodyTypeModel) => ListTile(
onTap: () {
setState(() {
_collapse();
kasaTipi = vehicleBodyTypeModel.vehicleBodyType;
});
if (kDebugMode) {
print(vehicleBodyTypeModel.vehicleBodyType);
}
},
leading: const Icon(
Icons.stars_outlined,
size: 10,
),
title: Text(vehicleBodyTypeModel.vehicleBodyType.toString()),
); // Araç kasa tipi
Widget buildTradeMark(TradeMarkModel tradeMarkModel) => ListTile(
onTap: () {
setState(() {
_collapse();
marka = tradeMarkModel.tradeMarkName;
});
if (kDebugMode) {
print(tradeMarkModel.tradeMarkName);
}
},
leading: const Icon(
Icons.stars_outlined,
size: 10,
),
title: Text(tradeMarkModel.tradeMarkName.toString()),
); // Araç MArka
Widget buildModel(VehicleModel vehicleModel) => ListTile(
onTap: () {
setState(() {
_collapse();
model = vehicleModel.modelName;
});
if (kDebugMode) {
print(vehicleModel.modelName);
}
},
leading: const Icon(
Icons.stars_outlined,
size: 10,
),
title: Text(vehicleModel.modelName.toString()),
); // Araç Modeli
Widget buildYear(VehicleYearModel vehicleYearModel) => ListTile(
onTap: () {
setState(() {
_collapse();
yil = vehicleYearModel.year;
});
if (kDebugMode) {
print(vehicleYearModel.year);
}
},
leading: const Icon(
Icons.stars_outlined,
size: 10,
),
title: Text(vehicleYearModel.year.toString()),
); // Araç Yılı
Widget buildProgress() => StreamBuilder<TaskSnapshot>(
stream: uploadTask?.snapshotEvents,
builder: (context, snapshot) {
if (snapshot.hasData) {
final data = snapshot.data!;
double progress = data.bytesTransferred / data.totalBytes;
return SizedBox(
height: 50,
child: Stack(
fit: StackFit.expand,
children: [
LinearProgressIndicator(
value: progress,
color: Colors.green,
backgroundColor: Colors.grey,
),
Center(
child: Text(
'${(100 * progress).roundToDouble()} %',
style: const TextStyle(color: Colors.white),
),
)
],
),
);
} else {
return const SizedBox(
height: 50,
);
}
},
);
}
I don't know which variable is causing the problem. I'm inexperienced in flutter.
The error message says on which line the error is. See
That means it's on line 297. If I'm not mistaken that is the line:
child: Image.file(File(pickedFile!.path!),
So pickedFile is null

how i solve this issue on flutter

when I am debug this its shown a error on search bar when I try to text on emulator here is the code please resolve this thanks
LateInitializationError: Field 'name' has not been initialized.
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
#override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
String url = "https://owlbot.info/api/v4/dictionary/";
String token = "7ba05536bd11ff8e22800cbda80951376c59ed84";
TextEditingController textEditingController = TextEditingController();
late StreamController _streamController;
late Stream _stream;
late Timer _debounce;
searchText() async {
if (textEditingController.text == null ||
textEditingController.text.isEmpty) {
_streamController.add(null);
return;
}
_streamController.add("waiting");
Uri uri = Uri.parse(url+textEditingController.text.trim());
http.Response response = await http.get (uri, headers: {"Authorization": "Token " + token});
_streamController.add(json.decode(response.body));
}
#override
void initState() {
super.initState();
_streamController = StreamController();
_stream=_streamController.stream;
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.green,
title: Text(
"Dictionery",
style: TextStyle(color: Colors.white),
),
centerTitle: true,
bottom: PreferredSize(
preferredSize: Size.fromHeight(45),
child: Row(
children: [
Expanded(
child: Container(
margin: const EdgeInsets.only(left: 12, bottom: 11),
decoration:
BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(24),
),
child: TextFormField(
onChanged: (String text) {
if (_debounce.isActive) _debounce.cancel();
_debounce = Timer(const Duration(milliseconds: 1000), () {
searchText();
},
);
},
controller: textEditingController,
decoration: InputDecoration(
hintText: "Search for Word",
contentPadding: const EdgeInsets.only(left: 24),
border: InputBorder.none,
),
),
),
),
IconButton(
icon:Icon(
Icons.search,
color: Colors.white,
),
onPressed: (){
searchText();
},
),
],
),
),
),
body: Container(
margin: EdgeInsets.all(8.0),
child: StreamBuilder(
builder:(BuildContext context, AsyncSnapshot snapshot){
if(snapshot.data== null)
{
return Center(
child: Text('Enter A Search Word'),
);
}
if(snapshot.data == "waiting"){
return Center(
child: CircularProgressIndicator(),
);
}
return ListView.builder(
itemCount: snapshot.data["defination"].length,
itemBuilder: (BuildContext context , int index)
{
return ListBody(
children: [
Container(
color: Colors.grey[300],
child: ListTile(
leading:snapshot.data["definations"][index]["image_url"] == null
? null:
CircleAvatar(
backgroundImage: NetworkImage(snapshot.data["definations"][index]["image_url"]),
),
title: Text(textEditingController.text.trim()
+"(" + snapshot.data["definations"][index]["type"]+")"),
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
snapshot.data["defination"][index]["defination"]),
)
],
);
},
);
},
stream: _stream,
),
),
);
}
}
when i debug this and touch on screen for text its give me error late initialization
Current issue is _debounce has not been initialized. Instead of late, make it nullable Timer? _debounce;.
And changes will be
child: TextFormField(
onChanged: (String text) async {
if (_debounce != null && _debounce!.isActive) {
_debounce!.cancel();
_debounce = Timer(
const Duration(milliseconds: 1000),
() async {
await searchText();
},
);
}
},
Full snippet
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
#override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
String url = "https://owlbot.info/api/v4/dictionary/";
String token = "7ba05536bd11ff8e22800cbda80951376c59ed84";
TextEditingController textEditingController = TextEditingController();
late StreamController _streamController;
late Stream _stream;
Timer? _debounce;
Future<void> searchText() async {
if (textEditingController.text.isEmpty) {
_streamController.add(null);
return;
}
_streamController.add("waiting");
Uri uri = Uri.parse(url + textEditingController.text.trim());
http.Response response =
await http.get(uri, headers: {"Authorization": "Token " + token});
_streamController.add(json.decode(response.body));
}
#override
void initState() {
super.initState();
_streamController = StreamController();
_stream = _streamController.stream;
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.green,
title: Text(
"Dictionery",
style: TextStyle(color: Colors.white),
),
centerTitle: true,
bottom: PreferredSize(
preferredSize: Size.fromHeight(45),
child: Row(
children: [
Expanded(
child: Container(
margin: const EdgeInsets.only(left: 12, bottom: 11),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(24),
),
child: TextFormField(
onChanged: (String text) async {
if (_debounce != null && _debounce!.isActive) {
_debounce!.cancel();
_debounce = Timer(
const Duration(milliseconds: 1000),
() async {
await searchText();
},
);
}
},
controller: textEditingController,
decoration: InputDecoration(
hintText: "Search for Word",
contentPadding: const EdgeInsets.only(left: 24),
border: InputBorder.none,
),
),
),
),
IconButton(
icon: Icon(
Icons.search,
color: Colors.white,
),
onPressed: () {
searchText();
},
),
],
),
),
),
body: Container(
margin: EdgeInsets.all(8.0),
child: StreamBuilder(
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.data == null) {
return Center(
child: Text('Enter A Search Word'),
);
}
if (snapshot.data == "waiting") {
return Center(
child: CircularProgressIndicator(),
);
}
return ListView.builder(
itemCount: snapshot.data["defination"].length,
itemBuilder: (BuildContext context, int index) {
return ListBody(
children: [
Container(
color: Colors.grey[300],
child: ListTile(
leading: snapshot.data["definations"][index]
["image_url"] ==
null
? null
: CircleAvatar(
backgroundImage: NetworkImage(snapshot
.data["definations"][index]["image_url"]),
),
title: Text(textEditingController.text.trim() +
"(" +
snapshot.data["definations"][index]["type"] +
")"),
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
snapshot.data["defination"][index]["defination"]),
)
],
);
},
);
},
stream: _stream,
),
),
);
}
}

How do i display progress bar on each item in the listview using flutter

i have a json data which am displaying in the listview that contains item name, scores and target scores. i want to show a progress bar indicating scored points and the target points below is my code and images to help understand.
This is my json data
Below is My code:
`
import 'dart:convert';
import 'package:network/network.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class FavouriteTab extends StatefulWidget {
#override
_FavouriteTabState createState() => _FavouriteTabState();
}
class _FavouriteTabState extends State<FavouriteTab> {
List products = List();
Future getAllProducts() async {
var response = await http.get(NetworkUrl.getProducts());
if (response.statusCode == 200) {
setState(() {
products = json.decode(response.body);
});
return products;
}
}
#override
void initState() {
super.initState();
getAllProducts();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Target Scores"),
),
body: FutureBuilder(
future: getAllProducts(),
builder: (context, snapshot) {
if (snapshot.hasData) {
if (products.contains("empty")) {
return Center(child: Text("NO DATA"));
} else {
return ListView.builder(
itemCount: products.length,
itemBuilder: (context, index) {
var notis = products;
var scoredAmt = notis[index]['scored_amt'];
var targetAmt = notis[index]['target_score'];
var _percentages = (scoredAmt / targetAmt);
return Card(
child: Container(
child: Column(
children: [
Text(notis[index]['item_name']),
Text(
notis[index]['target_score'],
style: TextStyle(color: Colors.indigo),
),
SizedBox(height: 5),
Row(
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Text("Scored Amount :" +
notis[index]['scored_amt']),
),
Spacer(),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text("Target Amount :" +
notis[index]['target_score']),
),
],
),
Padding(
padding: const EdgeInsets.all(8.0),
child: SizedBox(
width: 300,
height: 30,
child: LinearProgressIndicator(
value: _percentages)),
),
],
),
),
);
});
}
} else {
return LinearProgressIndicator(
backgroundColor: Colors.purpleAccent,
);
}
}),
);
}
}`
Am getting this error
i want to have data display like this according to the scores:
This is how i want to display
I don't know what am doing wrong kindly help
As the error you are getting denotes it seems that you are not parsing the strings as num's and are trying to divide Strings.
var _percentages = (num.tryParse(scoredAmt) / num.tryParse(targetAmt))
Or even better do that parsing in your model see here.
Also you are calling the getAllProducts in initState but are not caching the result and you call it again in the futureBuilder,
import 'dart:convert';
import 'package:Habapay/network/network.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class FavouriteTab extends StatefulWidget {
#override
_FavouriteTabState createState() => _FavouriteTabState();
}
class _FavouriteTabState extends State<FavouriteTab> {
List products = List();
Future allProducts;
Future getAllProducts() async {
var response = await http.get(NetworkUrl.getProducts());
if (response.statusCode == 200) {
setState(() {
products = json.decode(response.body);
});
return products;
}
}
#override
void initState() {
super.initState();
allProducts= getAllProducts();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Target Scores"),
),
body: FutureBuilder(
future: allProducts,/// Now the future gets called only once
builder: (context, snapshot) {
if (snapshot.hasData) {
if (products.contains("empty")) {
return Center(child: Text("NO DATA"));
} else {
return ListView.builder(
itemCount: products.length,
itemBuilder: (context, index) {
var notis = products;
var scoredAmt = notis[index]['scored_amt'];
var targetAmt = notis[index]['target_score'];
var _percentages = (scoredAmt / targetAmt);
return Card(
child: Container(
child: Column(
children: [
Text(notis[index]['item_name']),
Text(
notis[index]['target_score'],
style: TextStyle(color: Colors.indigo),
),
SizedBox(height: 5),
Row(
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Text("Scored Amount :" +
notis[index]['scored_amt']),
),
Spacer(),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text("Target Amount :" +
notis[index]['target_score']),
),
],
),
Padding(
padding: const EdgeInsets.all(8.0),
child: SizedBox(
width: 300,
height: 30,
child: LinearProgressIndicator(
value: _percentages)),
),
],
),
),
);
});
}
} else {
return LinearProgressIndicator(
backgroundColor: Colors.purpleAccent,
);
}
}),
);
}
}`

Generate gridView from an http request json response

the aim is to create a gridView of x elements, where x is dynamic because depends from the answer I receive from http request.
I know how to create a base gridView and how to print the result of my http request, but I've not understood how can I do both things: read json response, count how many elements I hava to create, create all elements with their names.
Here is the code:
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'utils/Request.dart';
class MyGames extends StatelessWidget {
// ### Sono i parametri che invio al php nella richiesta
static var requestBody = {"action": "getMyGames", "id_utente": "1"};
Future<Response> richiesta = makeRequest(requestBody);
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey[850],
body:
GridView.count(crossAxisCount: 1, childAspectRatio: (2.5), children: [
FutureBuilder<Response>(
future: richiesta,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Padding(
padding: EdgeInsets.all(10),
child: Container(
decoration: new BoxDecoration(
color: Colors.green[200],
),
child: Center(
child: Text(
snapshot.data.result[0]['name'](),
style: TextStyle(
color: Colors.grey[800],
),
),
),
));
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
return CircularProgressIndicator();
},
),
]),
);
}
}
Thanks!
I've solved this way:
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'utils/Request.dart';
class MyGames extends StatelessWidget {
// ### Sono i parametri che invio al php nella richiesta
static var requestBody = {"action": "getMyGames", "id_utente": "1"};
Future<Response> richiesta = makeRequest(requestBody);
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey[850],
body: FutureBuilder<Response>(
future: richiesta,
builder: (context, snapshot) {
if (snapshot.hasData) {
final List<Widget> listone =
snapshot.data.result.map<Widget>((el) => tile(el)).toList();
return GridView.extent(
maxCrossAxisExtent: 250,
children: listone,
);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
return CircularProgressIndicator();
},
),
);
}
Widget tile(el) {
return Padding(
padding: EdgeInsets.all(10),
child: Container(
decoration: new BoxDecoration(
color: Colors.green[200],
),
child: Center(
child: Text(
el['nomeGioco'],
style: TextStyle(
color: Colors.grey[800],
),
), /*Center(
child: Text('Item $index',
style: Theme.of(context).textTheme.headline5)),*/
),
));
}
}

Showing selected image in alert dialog in flutter

How can i show the selected image in my alert dialog ?
In my app, i added an alert dialog which has the camera button. When user clicks the camera button, another alert dialog asks to select file from gallery. After the user selects image file from gallery, i want to show the image in the alert dialog with the camera button, but the image shows only after reopening the alert dialog.
I have posted my code below. I am new to flutter. Please can someone help me? Thanks in advance.
class Test extends StatefulWidget {
#override
_State createState() => new _State();
}
Future<File> imageFile;
class _State extends State<Test> {
Future<void> _openDailog() async {
return showDialog<void>(
context: context,
barrierDismissible: true,
builder: (BuildContext context) {
return AlertDialog(
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(8.0)),
title: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text('Click Photo'),
Ink(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(24.0),
color: Colors.blue),
child: IconButton(
color: Colors.white,
icon: Icon(Icons.camera_alt),
onPressed: () {
_cameraOptions();
print("test");
},
),
)
],
),
content: SingleChildScrollView(
child: Container(
width: 300.0,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
showImage(),
InkWell(
child: Container(
margin: EdgeInsets.only(top: 8.0),
child: RaisedButton(
color: Colors.blue,
child: new Text(
"Send",
style: TextStyle(color: Colors.white),
),
onPressed: () {
Navigator.of(context).pop();
print("test");
},
),
)),
],
),
),
),
);
},
);
}
#override
Widget build(BuildContext context) {
// TODO: implement build
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
FloatingActionButton(
heroTag: null,
child: Icon(Icons.insert_drive_file),
onPressed: () {
_openDailog();
},
)
],
);
}
Future<void> _cameraOptions() {
return showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
content: new SingleChildScrollView(
child: new ListBody(
children: <Widget>[
FlatButton(
onPressed: () {
pickImageFromGallery(ImageSource.gallery);
Navigator.of(context).pop();
},
color: Colors.transparent,
child: new Text(
'Select From Gallery',
textAlign: TextAlign.start,
style: new TextStyle(
decoration: TextDecoration.underline,
),
),
),
],
),
),
);
});
}
pickImageFromGallery(ImageSource source) {
setState(() {
imageFile = ImagePicker.pickImage(source: source);
});
}
Widget showImage() {
return FutureBuilder<File>(
future: imageFile,
builder: (BuildContext context, AsyncSnapshot<File> snapshot) {
if (snapshot.connectionState == ConnectionState.done &&
snapshot.data != null) {
return Image.file(
snapshot.data,
width: MediaQuery.of(context).size.width,
height: 100,
);
} else if (snapshot.error != null) {
return const Text(
'Error Picking Image',
textAlign: TextAlign.center,
);
} else {
return const Text(
'No Image Selected',
textAlign: TextAlign.center,
);
}
},
);
}
}
That is because you would need to setState() however you can't do that in an alert dialogue as it doesn't have its own state, the workaround for that would be to have the dialogue be its own stateful widget. Please check out this article as it shows how to do that. If you faced problems let me know!
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path_provider/path_provider.dart';
void main() {
runApp(new MaterialApp(
home: new MyHomePage(),
));
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _selectedIndex = 0;
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(
title: Text("StackoverFlow"),
),
body: Container(),
floatingActionButton: FloatingActionButton(
onPressed: () async {
await _dialogCall(context);
},
),
);
}
Future<void> _dialogCall(BuildContext context) {
return showDialog(
context: context,
builder: (BuildContext context) {
return MyDialog();
});
}
}
class MyDialog extends StatefulWidget {
#override
_MyDialogState createState() => new _MyDialogState();
}
class _MyDialogState extends State<MyDialog> {
String imagePath;
Image image;
#override
Widget build(BuildContext context) {
return AlertDialog(
content: new SingleChildScrollView(
child: new ListBody(
children: <Widget>[
Container(child: image!= null? image:null),
GestureDetector(
child: Row(
children: <Widget>[
Icon(Icons.camera),
SizedBox(width: 5),
Text('Take a picture '),
],
),
onTap: () async {
await getImageFromCamera();
setState(() {
});
}),
Padding(
padding: EdgeInsets.all(8.0),
),
],
),
),
);
}
Future getImageFromCamera() async {
var x = await ImagePicker.pickImage(source: ImageSource.camera);
imagePath = x.path;
image = Image(image: FileImage(x));
}
}
Try this solution with GestureDetector() .it works
onTap:()async{
var image = await ImagePicker.pickImage(
source: ImageSource.gallery).whenComplete((){
setState(() {
});
}
);
setState(() {
_image = image;
});
},