Flutter:How to convert Cards UI or View to Individual View Please find the HomeScreen Page code and try to convert to detailed individual view - firebase

Flutter:How to convert Cards UI or View to Individual View Please find the HomeScreen Page code and try to convert to detailed individual view
import 'dart:async';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';
import 'package:gadjet_inventory/Form/ListTiles.dart';
import 'package:gadjet_inventory/main.dart';
import 'package:intl/intl.dart';
import 'package:gadjet_inventory/Form/Data.dart';
import 'UploadData.dart';
import 'package:pdf_flutter/pdf_flutter.dart';
// ignore: must_be_immutable
class HomeScreen extends StatefulWidget {
#override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
List<Data> dataList = [];
List<bool> favList = [];
bool searchState = false;
FirebaseAuth auth = FirebaseAuth.instance;
#override
void initState() {
// TODO: implement initState
super.initState();
DatabaseReference referenceData = FirebaseDatabase.instance.reference().child("Data");
referenceData.once().then((DataSnapshot dataSnapShot) {
dataList.clear();
favList.clear();
var keys = dataSnapShot.value.keys;
var values = dataSnapShot.value;
for (var key in keys) {
Data data = new Data(
values [key]['imgUrl'],
values [key]['wcpdfUrl'],
values [key]['ugpdfUrl'],
values [key]['cattegorrytype'],
values [key]['companyname'],
values [key]['modelname'],
values [key]['seriesname'],
values [key]['year'],
key
//key is the uploadid
);
dataList.add(data);
auth.currentUser().then((value) {
DatabaseReference reference = FirebaseDatabase.instance.reference().child("Data").child(key).child("Fav")
.child(value.uid).child("state");
reference.once().then((DataSnapshot snapShot){
if(snapShot.value!=null){
if(snapShot.value=="true"){
favList.add(true);
}else{
favList.add(false);
}
}else{
favList.add(false);
}
});
});
}
Timer(Duration(seconds: 1),(){
setState(() {
//
});
});
});
}
int selectedRadioTile;
String get path => null;
String get title => null;
setSelectedRadioTile(int val) {
setState(() {
selectedRadioTile = val;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.lightGreen,
//Color(0xffffffff),
appBar: AppBar(
centerTitle: true,
backgroundColor: Colors.blue,
title: new Text("Device Details", style:
TextStyle(fontSize: 20), textAlign: TextAlign.center),
actions: <Widget>[
IconButton(icon: Icon(Icons.refresh, size: 36, color: Colors.white,),
onPressed: () {
//debugPrint("Add New Device Cattegorry");
Navigator.push(context, MaterialPageRoute(builder: (context) {
return ListTiles();
}
)
); //
},
),
IconButton(icon: Icon(Icons.home, size: 36, color: Colors.white,),
onPressed: () {
//debugPrint("Add New Device Cattegorry");
Navigator.push(context, MaterialPageRoute(builder: (context) {
return MyHomePage();
}
)
); //
},
)
],),
body: dataList.length == 0
? Center(
child: Text("No Data Available", style: TextStyle(fontSize: 30),))
: ListView.builder(
itemCount: dataList.length,
itemBuilder: (_, index) {
return CardUI(dataList[index].imgUrl,dataList[index].wcpdfUrl, dataList[index].cattegorrytype,
dataList[index].companyname, dataList[index].modelname,dataList[index].seriesname,dataList[index].year,
dataList[index].uploadid,index);
}
),
);
}
Widget CardUI(String imgUrl, String wcpdfUrl,String cattegorrytype, String companyname, String modelname,
String seriesname, String year ,
String uploadId,int index) {
return Card(
elevation: 7,
margin: EdgeInsets.all(15),
//color: Color(0xffff2fc3),
color:Colors.blueGrey,
child: Container(
color: Colors.white,
margin: EdgeInsets.all(1.5),
padding: EdgeInsets.all(10),
child: Column(
children: <Widget>[
Image.network(
imgUrl != null
? imgUrl
: '',
width: 500,
height: 500,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Expanded(
flex: 1,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text( "Cattegorry Type:- "
"$cattegorrytype",
style: TextStyle(color: Colors.black),
),
),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Expanded(
flex: 1,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Theme(
data: ThemeData(
hintColor: Colors.blue,
),
child: Text( "Company Name:- "
"$companyname",
style: TextStyle(color: Colors.black),
),
),
),
),
Expanded(
flex: 1,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Theme(
data: ThemeData(
hintColor: Colors.blue,
),
child: Text( "Model Name:- "
"$modelname",
style: TextStyle(color: Colors.black),
),
),
),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Expanded(
flex: 1,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Theme(
data: ThemeData(
hintColor: Colors.blue,
),
child: Text( "Series Name:- "
"$seriesname",
style: TextStyle(color: Colors.black),
),
),
),
),
Expanded(
flex: 1,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Theme(
data: ThemeData(
hintColor: Colors.blue,
),
child: Text( "Year Of MFG:- "
"$year",
style: TextStyle(color: Colors.black),
),
),
),
),
],
),
RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
color: Colors.blue,
child: Text("Warranty Card",
style: TextStyle(fontSize: 18, color: Colors.white),),
),
RadioListTile(
value: 1,
groupValue: selectedRadioTile,
title: Text("PDF"),
//subtitle: Text("Upload PDF File"),
/* onChanged: (val) {
filePicker(context);
},*/
activeColor: Colors.red,
),
Padding(padding: EdgeInsets.only(top: 15)),
// _buildPDF1Field(context),
PDF.network(
wcpdfUrl != null
? wcpdfUrl
: '',
width: 600,
height: 1000, placeHolder: Image.asset("assets/images/pdf.png",
height: 600, width: 500),
),
SizedBox(height: 24),
],
),
),
);
}
I have uploaded few text items one imageUrl and one pdf document to firebase storage and able to retrieve them in HomeScreen View (card UI or View (cards list) and List Tile View( with one image and one text, when tapped on it should show each individual view).
Please guide me How to convert to Individual Retrieving page instead of group of vertical cards list.

Related

Search bar in flutter app fetch articles from WordPress API

I guys, I have a News Flutter app that fetch articles from WordPress API,I have this code in my app but I don't know how to show up articles from search bar.
As you can see in the body of the Home page I have a busy body homepage because there are tabs widgets to show up.
I share screens to understand my case.
Is there another way to show up results maybe using a search delegate?
HomePage
searchbar page
Empty searchbar when I search keyword, no results
Home screen with tabs to load
class SearchBar extends StatefulWidget{
final List<Article> posts;
const SearchBar({Key? key, required this.posts,}) : super(key: key);
#override
_SearchBarState createState() => _SearchBarState();
}
class _SearchBarState extends State<SearchBar> {
final List<Article> _searchedPost = [];
late List<Article> _searchedArticles = [];
late final data;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: TextField(
decoration: const InputDecoration(
hintText: "Cerca Articolo",
border: InputBorder.none,
),
onChanged: (val) {
setState(() {
_searchedArticles = widget.posts.where((element) => element.title!.contains(val)).toList();
});
},
),
),
body: _searchedArticles.isEmpty ?
Scaffold(
body: Padding(padding: const EdgeInsets.all(12),
child: Column(
children: [
Image.asset("assets/images/search-illustration.png", height: 230,),
const SizedBox(height: 20,),
const Text('Nessun articolo trovato!',
style: TextStyle(
fontSize: 20.0,
color: Colors.black,
fontWeight: FontWeight.w600,
),
),
const SizedBox(height: 20,),
const Text('Inserisci meglio le lettere o parole chiave dell’articolo che stai cercando e riprova.',
style: TextStyle(
fontSize: 16.0,
color: Colors.black54,
fontWeight: FontWeight.w400,
),
),
const SizedBox(height: 30,),
MaterialButton(
height: 50,
elevation: 0,
color: Colors.blue[900],
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
child: Row(
children: const [
Text('Torna alla home', style: TextStyle(fontSize: 16.0, fontWeight: FontWeight.w600),),
],
),
onPressed: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => HomePage(),
),
);
},
),
],
),
),
) : ListView.builder(
itemCount: _searchedArticles.length,
itemBuilder: (context, i) {
return Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Card(
margin: const EdgeInsets.all(10),
elevation: 5,
shadowColor: Colors.black26,
child: InkWell(
child: ClipRRect(
borderRadius: BorderRadius.circular(10),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
//data["_embedded"]["wp:featuredmedia"][0]["link"],),
_searchedArticles[i].urlImage == null
? const Text("Nessuna immagine caricata")
: Image.network(data["_embedded"]["wp:featuredmedia"][0]["link"],
width: double.infinity,
height: 220,
fit: BoxFit.cover,
),
// Title article
Column(
children: [
Padding(
padding: const EdgeInsets.only(
left: 16, top: 16, bottom: 16),
child: Row(
children: [
Expanded(
child: Text(_searchedArticles[i].title as String,
maxLines: 3,
overflow: TextOverflow.clip,
softWrap: true,
style: const TextStyle(
fontSize: 18,
fontWeight: FontWeight.w600,
,
),
),
),
],
),
)
],
),
],
),
),
onTap: () {
if (_searchedPost[i] != null) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ArticlePage(
data: _searchedPost[i],
),
),
);
}
},
),
),
],
);
},
),
);
}
}```
Home page
class HomePage extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<HomePage> with SingleTickerProviderStateMixin {
TabController? _tabController;
final List<Tab> topTabs = <Tab>[
const Tab(child: Text("Notizie")),
const Tab(child: Text("Fiscalità")),
const Tab(child: Text("Gestione")),
const Tab(child: Text("Business")),
const Tab(child: Text("Documentazione")),
];
#override
void initState() {
/// Start tabs articles
_tabController = TabController(length: topTabs.length, initialIndex: 0, vsync: this)..addListener(() {setState(() {});});
super.initState();
/// End tabs articles
}
/// tabs
Future<bool> _onWillPop() async {
if (_tabController?.index == 0) {
await SystemNavigator.pop();
}
Future.delayed(const Duration(microseconds: 200), () {
_tabController?.index = 0;
});
return _tabController?.index == 0;
}
final _scaffoldKey = GlobalKey<ScaffoldState>();
///
///
/// Search page
final List<Article> _posts = [];
#override
Widget build(BuildContext context) {
return Container(
child: WillPopScope(
onWillPop: _onWillPop,
child: Scaffold(
key: _scaffoldKey,
extendBody: true,
drawer: NavbarMenu(),
backgroundColor: const Color(0xFFFAFAFA),
appBar: AppBar(
elevation: 0,
leading: Builder(
builder: (BuildContext context) {
return GestureDetector(
child: Center(
child: IconButton(
icon: const Icon(
Icons.dehaze_outlined,
color: Colors.white,
),
onPressed: () {
Scaffold.of(context).openDrawer();
},
),
),
);
},
),
backgroundColor: Colors.blue[900],
centerTitle: true,
title: Image.asset('assets/images/bird.png', fit: BoxFit.contain, height: 32,),
/// Action search icon
actions: <Widget>[
/// First search icon
IconButton(
icon: const Icon(Icons.search, color: Colors.white,),
onPressed: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (context)=> SearchBar(posts: _posts,)
));
},
),
],
/// Bottom tab bar
bottom: TabBar(
controller: _tabController,
indicatorColor: const Color(0xFFF9E14B),
tabs: topTabs,
indicator: const UnderlineTabIndicator(
borderSide: BorderSide(
width: 4.0,
color: Color(0xFFF9E14B),
),
insets: EdgeInsets.symmetric(horizontal: 10.0, vertical: 0),
),
labelColor: Colors.yellow,
unselectedLabelColor: Colors.white,
isScrollable: true,
labelStyle: const TextStyle(
fontWeight: FontWeight.w600,
fontSize: 16,
fontFamily: "Raleway"),
unselectedLabelStyle: const TextStyle(
fontWeight: FontWeight.w400,
fontSize: 14,
),
),
),
/// Body
body: TabBarView(
controller: _tabController,
children: const [
//SearchBar(posts: [],),
NewsPage(),
FiscalitaPage(),
GestionePage(),
BusinessPage(),
DocumentazionePage(),
],
),
///
),
),
);
}```

Flutter: Firebase Storage is not uploading multiple images, it always repeat the same path?

class CategoryScreen extends StatefulWidget {
static const routeName = '/category-screen';
#override
_CategoryScreenState createState() => _CategoryScreenState();
}
class _CategoryScreenState extends State<CategoryScreen> {
#override
Widget build(BuildContext context) {
//from co_detai_screen.dart
final companyId = ModalRoute.of(context).settings.arguments as String;
//
final _form = GlobalKey<FormState>();
String _car = '';
String _carModel = '';
File carImage;
String ranDom = randomBetween(0, 300).toString();
void _submitCarCategory() async{
final isValid = _form.currentState.validate();
if(isValid){
_form.currentState.save();
//.... upload image here
/*===============================Here is firebase storage work==============================*/
final ref = FirebaseStorage.instance.ref().child('cars').child(ranDom + '.jpg');
await ref.putFile(carImage);
//kan fe .onComplete ba3ed (image)**strong text**
//.... upload image here
//... now want to get this image into the firestore
final url = await ref.getDownloadURL();
//... now want to get this image into the firestore
FirebaseFirestore.instance.collection('companies').doc(companyId).collection('category').doc().set(({
'carName': _car,
'carModel': _carModel,
'car_image': url
}));
Navigator.of(context).pop();
}
}
void _pickedImage(File image){
carImage = image;
}
void _showDialog(){
showDialog(context: context, builder: (context)=> AlertDialog(
title: Text('Add Category'),
content: SingleChildScrollView(
child: Form(
key: _form,
child: Container(
height: 450,
width: double.infinity,
padding: EdgeInsets.all(20),
child: Column(
children: [
Text('Add Category', style: TextStyle(fontSize: 16),),
SizedBox(height: 10,),
UserImagePicker(_pickedImage),
TextFormField(decoration: InputDecoration(labelText: 'Car'),
onSaved: (value){
_car = value;
},
),
TextFormField(
decoration: InputDecoration(labelText: 'Car model'),
onSaved: (value){
_carModel = value;
},
),
SizedBox(height: 20,),
FlatButton(
onPressed: (){
_submitCarCategory();
},
child: Text('Add'),
color: Colors.indigo,
textColor: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20)
),
),
],
),
),
),
),
),
);
}
return FutureBuilder(
future: FirebaseFirestore.instance.collection('companies').doc(companyId).get(),
builder: (ctx, futureSnapshot){
if(futureSnapshot.hasData){
return Scaffold(
appBar: AppBar(title: Row(
children: [
Text(futureSnapshot.data['coname']),
SizedBox(width: 5,),
Text('Category'),
],
),
),
body: Column(
children: [
SizedBox(height: 30,),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.only(left: 15.0),
child: FlatButton(
onPressed: ()=> _showDialog(),
child: Text('Add Category'),
color: Colors.indigo,
textColor: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20)
),
),
),
],
),
SizedBox(height: 10,),
Divider(),
SizedBox(height: 10,),
Expanded(
child: CategoryWidget(
//futurebuilder snapshot id
futureSnapshot.data.id
),
),
],
),
);
}else{
return Scaffold(
body: Center(child: CircularProgressIndicator()),
);
}
}
);
}
}
Instead of using
String ranDom = randomBetween(0, 300).toString();
Assign a Date and Time(including seconds) to your image name or combination of both ranDom and dateTime.
final ref = FirebaseStorage.instance.ref().child('cars').child(ranDom + DateTime + '.jpg');

I am unable to navigate to detail page from List Tile Page and show retrieved data of the particular item

I have uploaded few text items, image items and pdf documents to firebase database / storage and and able to retrieve all of them in HomeScreen i.e Vertical CardsUI list as well as ListTiles View with one image, one title and one subtitle.
But unable to build DetailView i.e One Singe Item's details instead of multipleCards and navigate to DetailView page
on click on any List Tile Item .
My code for HomeScreen.dart is as follows
import 'dart:async';
import 'dart:io';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:gadjet_inventory/Form/ListTileFeed.dart';
import 'package:gadjet_inventory/Form/ListTiles.dart';
import 'package:gadjet_inventory/Form/RetrievePage.dart';
import 'package:gadjet_inventory/main.dart';
import 'package:intl/intl.dart';
import 'package:gadjet_inventory/Form/Data.dart';
import 'UploadData.dart';
import 'package:pdf_flutter/pdf_flutter.dart';
// ignore: must_be_immutable
import 'package:url_launcher/url_launcher.dart';
class HomeScreen extends StatefulWidget {
#override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
List<Data> dataList = [];
List<bool> favList = [];
bool searchState = false;
FirebaseAuth auth = FirebaseAuth.instance;
String get data => null;
#override
void initState() {
// TODO: implement initState
super.initState();
DatabaseReference referenceData = FirebaseDatabase.instance.reference().child("Data");
referenceData.once().then((DataSnapshot dataSnapShot) {
dataList.clear();
favList.clear();
var keys = dataSnapShot.value.keys;
var values = dataSnapShot.value;
for (var key in keys) {
Data data = new Data(
values [key]['imgUrl'],
values [key]['wcimgUrl'],
values [key]['wcpdfUrl'],
values [key]['cattegorrytype'],
values [key]['companyname'],
values [key]['modelname'],
values [key]['seriesname'],
values [key]['serielnumber'],
key
//key is the uploadid
);
dataList.add(data);
auth.currentUser().then((value) {
DatabaseReference reference = FirebaseDatabase.instance.reference().child("Data").child(key).child("Fav")
.child(value.uid).child("state");
reference.once().then((DataSnapshot snapShot){
if(snapShot.value!=null){
if(snapShot.value=="true"){
favList.add(true);
}else{
favList.add(false);
}
}else{
favList.add(false);
}
});
});
}
Timer(Duration(seconds: 1),(){
setState(() {
//
});
});
});
}
int selectedRadioTile;
String get path => null;
String get title => null;
setSelectedRadioTile(int val) {
setState(() {
selectedRadioTile = val;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.lightGreen,
//Color(0xffffffff),
appBar: AppBar(
centerTitle: true,
backgroundColor: Colors.blue,
title: new Text("Device Details", style:
TextStyle(fontSize: 20), textAlign: TextAlign.center),
),
body: dataList.length == 0
? Center(
child: Text("No Data Available", style: TextStyle(fontSize: 30),))
: ListView.builder(
itemCount: dataList.length,
itemBuilder: (_, index) {
return CardUI(dataList[index].imgUrl,dataList[index].wcimgUrl, ,dataList[index].wcpdfUrl, dataList[index].cattegorrytype,
dataList[index].companyname, dataList[index].modelname,dataList[index].seriesname, dataList[index].uploadid,index);
}
),
);
}
Widget CardUI(String imgUrl, String wcimgUrl, String wcpdfUrl, String cattegorrytype, String companyname, String modelname,
String seriesname String uploadId,int index) {
return Card(
elevation: 7,
margin: EdgeInsets.all(15),
//color: Color(0xffff2fc3),
color:Colors.blueGrey,
child: Container(
color: Colors.white,
margin: EdgeInsets.all(1.5),
padding: EdgeInsets.all(10),
child: Column(
children: <Widget>[
Image.network(
imgUrl != null
? imgUrl
: '',
width: 500,
height: 500,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Expanded(
flex: 1,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text( "Cattegorry Type:- "
"$cattegorrytype",
style: TextStyle(color: Colors.black),
),
),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Expanded(
flex: 1,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Theme(
data: ThemeData(
hintColor: Colors.blue,
),
child: Text( "Company Name:- "
"$companyname",
style: TextStyle(color: Colors.black),
),
),
),
),
Expanded(
flex: 1,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Theme(
data: ThemeData(
hintColor: Colors.blue,
),
child: Text( "Model Name:- "
"$modelname",
style: TextStyle(color: Colors.black),
),
),
),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Expanded(
flex: 1,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Theme(
data: ThemeData(
hintColor: Colors.blue,
),
child: Text( "Series Name:- "
"$seriesname",
style: TextStyle(color: Colors.black),
),
),
),
),
],
),
RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
color: Colors.blue,
child: Text("Warranty Card",
style: TextStyle(fontSize: 18, color: Colors.white),),
),
RadioListTile(
value: 1,
groupValue: selectedRadioTile,
title: Text("PDF"),
//subtitle: Text("Upload PDF File"),
/* onChanged: (val) {
filePicker(context);
},*/
activeColor: Colors.red,
),
Padding(padding: EdgeInsets.only(top: 15)),
// _buildPDF1Field(context),
PDF.network(
wcpdfUrl != null
? wcpdfUrl
: '',
width: 600,
height: 1000, placeHolder: Image.asset("assets/images/pdf.png",
height: 600, width: 500),
),
SizedBox(height: 24),
RadioListTile(
value: 2,
groupValue: selectedRadioTile,
title: Text("Image"),
//subtitle: Text("Upload W Card Image"),
/* onChanged: (val) {
openWCImagePickerModal(context);
//_startWCUpload();
},*/
activeColor: Colors.blue,
),
Padding(padding: EdgeInsets.only(top: 15)),
Image.network(
wcimgUrl != null
? wcimgUrl
: 'https://www.testingxperts.com/wp-content/uploads/2019/02/placeholder-img.jpg',
width: 500,
height: 500,
),
SizedBox(height: 24),
],
),
),
);
}
}.
Now my requirement is to show Detail View of single item when clciked on it in ListTiles , it should navigate to DetailPage and show me the details of that particular item.
How to build DetailView page ? and Navigate from ListTilePage
I have achieved this using seperate DetailView.dart page.
I have created DetailView.dart page separately like
class DetailView extends StatefulWidget {
#override
_DetailViewState createState() => _DetailViewState();
}
class _DetailViewState extends State<DetailView> {
List<Data> dataList = [];
List<bool> favList = [];
bool searchState = false;
FirebaseAuth auth = FirebaseAuth.instance;
String get data => null;
} etc

How to display and update multiple image in flutter

I want to display image from list of task which I pass the object of documentsnapshot into the edit task.
Here is my code.
ListOfTaskNotAccepted
import 'package:carousel_pro/carousel_pro.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:fyp/screen/RecordOfficer/EditTaskNotApprove.dart';
import 'package:fyp/shared/Loading.dart';
import 'package:google_fonts/google_fonts.dart';
class ListOfTaskNotAccepted extends StatefulWidget {
#override
_ListOfTaskNotAcceptedState createState() => _ListOfTaskNotAcceptedState();
}
final FirebaseAuth auth = FirebaseAuth.instance;
Stream<QuerySnapshot> getUser(BuildContext context) async* {
final FirebaseUser rd = await auth.currentUser();
yield* Firestore.instance.collection("Task").where('uid',isEqualTo: rd.uid).where("verified", isEqualTo: 'TidakSah').snapshots();
}
class _ListOfTaskNotAcceptedState extends State<ListOfTaskNotAccepted> {
List<NetworkImage> _listOfImages = <NetworkImage>[];
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Aduan Tidak Diterima"),
backgroundColor: Colors.redAccent,
),
body: Container(
child: StreamBuilder(
stream: getUser(context),
builder: (context, snapshot){
if (snapshot.hasError || !snapshot.hasData) {
return Loading();
} else{
return ListView.builder(
itemCount: snapshot.data.documents.length,
itemBuilder: (BuildContext context, int index){
DocumentSnapshot da = snapshot.data.documents[index];
_listOfImages =[];
for(int i =0; i <da['url'].length; i++){
_listOfImages.add(NetworkImage(da['url'][i]));
}
DateTime myDateTime = (da['date']).toDate();
return Card(
child:ListTile(
title: Container(
alignment: Alignment.centerLeft,
child: Column(
children: <Widget>[
SizedBox(height: 5.0),
Container(alignment: Alignment.centerLeft,
child: Row(
children: [
Text("Sumber Aduan: ", style: GoogleFonts.asap(fontWeight: FontWeight.bold)),
Text(da['sumberAduan'], style: GoogleFonts.asap(fontWeight: FontWeight.bold)),
],
),
),
SizedBox(height: 5.0),
Container(alignment: Alignment.centerLeft,
child: Row(
children: [
Text("Nombor Aduan: ", style: GoogleFonts.lato(fontWeight: FontWeight.bold)),
Text(da['noAduan'], style: GoogleFonts.lato(fontWeight: FontWeight.bold)),
],
),
),
SizedBox(height: 5.0),
Container(alignment: Alignment.centerLeft,
child: Row(
children: [
Text("Lokasi: ", style: GoogleFonts.lato(fontWeight: FontWeight.bold)),
Text(da['kawasan'] + " " + da['naJalan'], style: GoogleFonts.lato(fontWeight: FontWeight.bold)),
],
),
),
SizedBox(height: 5.0),
Container(alignment: Alignment.centerLeft,
child: Row(
children: [
Text("Kategori: ", style: GoogleFonts.arimo(fontWeight: FontWeight.w500)),
Text(da['kategori'], style: GoogleFonts.arimo(fontWeight: FontWeight.w500)),
],
),
),
Column(
children: [
Container(
margin: EdgeInsets.all(10.0),
height: 200,
decoration: BoxDecoration(
color: Colors.white
),
width: MediaQuery.of(context).size.width,
child: Carousel(
boxFit: BoxFit.cover,
images: _listOfImages,
autoplay: false,
indicatorBgPadding: 5.0,
dotPosition: DotPosition.bottomCenter,
animationCurve: Curves.fastLinearToSlowEaseIn,
animationDuration: Duration(milliseconds: 2000),
),
)
],
)
],
),
),
subtitle: Container(
child: Column(
children: [
SizedBox(height: 5.0),
Container(alignment: Alignment.centerLeft,
child: Row(
children: [
Text("Catatan: ", style: GoogleFonts.arimo(fontWeight: FontWeight.w500)),
Text(da['comments'], style: GoogleFonts.arimo(fontWeight: FontWeight.w500)),
],
),
),
],
),
),
onTap: () {Navigator.push(context, MaterialPageRoute(builder: (context) => EditTask(da:da)));}
)
);
});
}
}),
)
);
}
}
In this code, I pass the documentsnapshot da in navigator. here is my code EditTask
import 'dart:io';
import 'package:carousel_pro/carousel_pro.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
class EditTask extends StatefulWidget {
final DocumentSnapshot da;
const EditTask({Key key, this.da}) : super(key: key);
#override
_EditTaskState createState() => _EditTaskState(da);
}
class _EditTaskState extends State<EditTask> {
DocumentSnapshot da;
_EditTaskState(DocumentSnapshot da){
this.da = da;
}
TextEditingController _noAduan;
TextEditingController _sumberAduan;
TextEditingController _kategori;
String _listOfImages;
DateTime myDateTime = DateTime.now();
#override
void initState(){
super.initState();
_noAduan = TextEditingController(text: widget.da.data['noAduan']);
_sumberAduan =TextEditingController(text: widget.da.data['sumberAduan']);
_kategori = TextEditingController(text: widget.da.data['kategori']);
myDateTime = (da.data['date']).toDate();
_listOfImages = da.data['url'];
}
List <String> sumber = <String> ['Sistem Aduan MBPJ', 'Sistem Aduan Waze', 'Sistem Aduan Utiliti'];
List <String> kate = <String> ['Segera', 'Pembaikan Biasa'];
String kategori;
String sumberAduan;
File image;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Kemaskini Aduan"),
backgroundColor: Colors.redAccent,
),
body: Container(
padding: const EdgeInsets.all(16.0),
child: Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
SizedBox(height: 10.0),
TextFormField(
decoration:InputDecoration(
hintText: myDateTime.toString(),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(5))),
onChanged: (value){
setState(() {
myDateTime = value as DateTime;
print(myDateTime);
});
},
),
SizedBox(height: 10.0),
TextFormField(
decoration:InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(5))),
controller: _noAduan,
),
SizedBox(height: 10.0),
DropdownButtonFormField(
hint:Text(widget.da.data['sumberAduan']),
decoration: InputDecoration(
prefixIcon: Icon(Icons.perm_contact_calendar),
border: OutlineInputBorder(borderRadius: BorderRadius.circular(5))),
isExpanded: true,
value: sumberAduan,
onChanged: (newValue) {
setState(() {
sumberAduan = newValue;
_sumberAduan.text = sumberAduan;
});
},
items: sumber.map((sum){
return DropdownMenuItem(
value: sum,
child: new Text(sum),
);
}).toList(),
),
SizedBox(height: 10.0),
DropdownButtonFormField(
hint:Text(widget.da.data['kategori']),
decoration: InputDecoration(
prefixIcon: Icon(Icons.perm_contact_calendar),
border: OutlineInputBorder(borderRadius: BorderRadius.circular(5))),
isExpanded: true,
value: kategori,
onChanged: (newValue) {
setState(() {
kategori = newValue;
_kategori.text = kategori;
});
},
items: kate.map((ka){
return DropdownMenuItem(
value: ka,
child: new Text(ka),
);
}).toList(),
),
SizedBox(height: 10.0),
Column(
children: [
Container(
margin: EdgeInsets.all(10.0),
height: 200,
decoration: BoxDecoration(
color: Colors.white
),
width: MediaQuery.of(context).size.width,
child: Carousel(
boxFit: BoxFit.cover,
autoplay: false,
images:Image.network(da.data['url']),
indicatorBgPadding: 5.0,
dotPosition: DotPosition.bottomCenter,
animationCurve: Curves.fastLinearToSlowEaseIn,
animationDuration: Duration(milliseconds: 2000),
),
)
],
)
],
),
),
)
);
}
}
The error show that
Error: The argument type 'Image' can't be assigned to the parameter type 'List'.
I had problem to display the image when user to want to edit specific task. I had tried many method to display specific image that user selected for updating. Is there anything method to display it? someone can explain please?
You have to provide a Image List. Look at the following exemple:
CarouselSlider(
options: CarouselOptions(height: 400.0),
items: [1,2,3,4,5].map((i) {
return Builder(
builder: (BuildContext context) {
return Container(
width: MediaQuery.of(context).size.width,
margin: EdgeInsets.symmetric(horizontal: 5.0),
decoration: BoxDecoration(
color: Colors.amber
),
child: Text('text $i', style: TextStyle(fontSize: 16.0),)
);
},
);
}).toList(),
)
You should change the way you are querying the images in the widget tree to something like the example above.
you can use
GridView.builder()
List imagesLinks = [
"first link",
"second link",
"third link",
"fourth link",
"fifth link",
"sixth link",
"seventh link",
];
GridView.builder(
padding: EdgeInsets.all(10),
physics: NeverScrollableScrollPhysics(),
shrinkWrap: true,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
crossAxisSpacing: 5.0,
mainAxisSpacing: 5.0,
),
itemCount: imageLinks.length,
itemBuilder: (context, index) {
return Column(
children: [
CircleAvatar(
radius: 30,
child:Image.network('${imageLinks[index]}'),
),
],
);
},
)

NoSuchMethodError: 'dart.global.firebase.auth' in the Flutter Chat App

I was creating this Chat App and after implementing the search function I encountered this NoSuchMethodError: tried to call a non-function, such as null: 'dart.global.firebase.auth' problem.
So basically now when I sign up the email and username doesn't get uploaded to firebase auth and Cloud Firestore, which earlier used to happen I think I did some mistake in the search.dart file which seems weird to me.
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:intro/helper/constants.dart';
import 'package:intro/services/database.dart';
import 'package:intro/widgets/widgets.dart';
import 'conversation_screen.dart';
class SearchScreen extends StatefulWidget {
#override
_SearchScreenState createState() => _SearchScreenState();
}
class _SearchScreenState extends State<SearchScreen> {
DatabaseMethods databaseMethods = new DatabaseMethods();
TextEditingController searchTextEditingController =
new TextEditingController();
QuerySnapshot searchSnapshot;
Widget searchList() {
return searchSnapshot != null
? ListView.builder(
itemCount: searchSnapshot.docs.length,
shrinkWrap: true,
itemBuilder: (context, index) {
return searchTile(
searchSnapshot.docs[index].data()["name"],
searchSnapshot.docs[index].data()["email"],
);
})
: Container();
}
initiateSearch() {
databaseMethods
.getUserByUsername(searchTextEditingController.text)
.then((val) {
setState(() {
searchSnapshot = val;
});
});
}
createChatroomAndStartConversation({String userName}) {
String chatRoomId = getChatRoomId(userName, Constants.myName);
List<String> users = [userName, Constants.myName];
Map<String, dynamic> chatRoomMap = {
"users": users,
"chatroomid": chatRoomId
};
DatabaseMethods().createChatRoom(chatRoomId, chatRoomMap);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ConversationScreen(),
));
}
Widget searchTile(String userName, String userEmail) {
return Container(
padding: EdgeInsets.symmetric(horizontal: 24, vertical: 16),
child: Row(
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(userName, style: mediumTextStyle()),
Text(userEmail, style: mediumTextStyle())
],
),
Spacer(),
GestureDetector(
onTap: () {
createChatroomAndStartConversation(userName: userName);
},
child: Container(
decoration: BoxDecoration(
color: Colors.blue, borderRadius: BorderRadius.circular(30)),
padding: EdgeInsets.symmetric(horizontal: 16, vertical: 6),
child: Text(
"Message",
style: mediumTextStyle(),
),
),
)
],
),
);
}
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: appBarMain(context),
body: Container(
child: Column(
children: [
Container(
color: Color(0x54FFFFFF),
padding: EdgeInsets.symmetric(horizontal: 24, vertical: 16),
child: Row(children: [
Expanded(
child: TextField(
controller: searchTextEditingController,
style: TextStyle(
color: Colors.white,
),
decoration: InputDecoration(
hintText: "Search Username",
hintStyle: TextStyle(
color: Colors.white54,
),
border: InputBorder.none),
),
),
GestureDetector(
onTap: () {
initiateSearch();
},
child: Container(
height: 35,
width: 35,
decoration: BoxDecoration(
gradient: LinearGradient(colors: [
const Color(0x36FFFFFF),
const Color(0x0FFFFFFF)
]),
borderRadius: BorderRadius.circular(30)),
padding: EdgeInsets.all(1),
child: Icon(
Icons.search,
color: Colors.white,
)),
)
]),
),
searchList()
],
),
),
);
}
}
getChatRoomId(String a, String b) {
if (a.substring(0, 1).codeUnitAt(0) > b.substring(0, 1).codeUnitAt(0)) {
return "$b\_$a";
} else {
return "$a\_$b";
}
}
and just in case there is an error with the signUp.dart file here it is.
import 'package:flutter/material.dart';
import 'package:intro/helper/helperfunctions.dart';
import 'package:intro/services/auth.dart';
import 'package:intro/services/database.dart';
import 'package:intro/widgets/widgets.dart';
import 'chatRoomsScreen.dart';
class SignUp extends StatefulWidget {
final Function toggle;
SignUp(this.toggle);
#override
_SignUpState createState() => _SignUpState();
}
class _SignUpState extends State<SignUp> {
bool isLoading = false;
AuthMethods authMethods = new AuthMethods();
DatabaseMethods databaseMethods = new DatabaseMethods();
final formKey = GlobalKey<FormState>();
TextEditingController userNameTextEditingController =
new TextEditingController();
TextEditingController emailTextEditingController =
new TextEditingController();
TextEditingController passwordTextEditingController =
new TextEditingController();
signMeUP() {
if (formKey.currentState.validate()) {
Map<String, String> userInfoMap = {
"name": userNameTextEditingController.text,
"email": emailTextEditingController.text,
};
HelperFunctions.saveUserEmailSharedPreference(
emailTextEditingController.text);
HelperFunctions.saveUserNameSharedPreference(
userNameTextEditingController.text);
setState(() {
isLoading = true;
});
authMethods
.signUpwithemailandpassword(emailTextEditingController.text,
passwordTextEditingController.text)
.then((value) {
// print("$value.uid");
databaseMethods.uploadUserInfo(userInfoMap);
HelperFunctions.saveUserLoggedInSharedPreference(true);
Navigator.pushReplacement(
context, MaterialPageRoute(builder: (context) => ChatRoom()));
});
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: appBarMain(context),
body: isLoading
? Container(
child: Center(child: CircularProgressIndicator()),
)
: SingleChildScrollView(
child: Container(
height: MediaQuery.of(context).size.height - 60,
alignment: Alignment.bottomCenter,
child: Container(
padding: EdgeInsets.symmetric(horizontal: 24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Form(
key: formKey,
child: Column(
children: [
TextFormField(
validator: (val) {
return val.isEmpty || val.length < 2
? "Invalid Username (Needs to be more than 2 characters)"
: null;
},
controller: userNameTextEditingController,
style: simpleTextStyle(),
decoration: textfieldInputDecoration("username"),
),
TextFormField(
validator: (val) {
return RegExp(
r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+#[a-zA-Z0-9]+\.[a-zA-Z]+")
.hasMatch(val)
? null
: "Enter correct email";
},
controller: emailTextEditingController,
style: simpleTextStyle(),
decoration: textfieldInputDecoration("email"),
),
TextFormField(
obscureText: true,
validator: (val) {
return val.length < 6
? "Please provide with 6+ character"
: null;
},
controller: passwordTextEditingController,
style: simpleTextStyle(),
decoration: textfieldInputDecoration("password"),
),
],
),
),
SizedBox(
height: 10,
),
Container(
alignment: Alignment.centerRight,
child: Container(
padding:
EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: Text(
"Forgot Password?",
style: simpleTextStyle(),
),
),
),
SizedBox(
height: 10,
),
GestureDetector(
onTap: () {
signMeUP();
},
child: Container(
alignment: Alignment.center,
width: MediaQuery.of(context).size.width,
padding: EdgeInsets.symmetric(vertical: 20),
decoration: BoxDecoration(
gradient: LinearGradient(colors: [
const Color(0xff007EF4),
const Color(0xff2A75BC)
]),
borderRadius: BorderRadius.circular(30)),
child: Text("Sign Up", style: mediumTextStyle()),
),
),
SizedBox(
height: 10,
),
Container(
alignment: Alignment.center,
width: MediaQuery.of(context).size.width,
padding: EdgeInsets.symmetric(vertical: 20),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(30)),
child: Text("Sign Up with Google",
style:
TextStyle(color: Colors.black, fontSize: 18)),
),
SizedBox(
height: 15,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"Already have an account? ",
style: mediumTextStyle(),
),
GestureDetector(
onTap: () {
widget.toggle();
},
child: Container(
padding: EdgeInsets.symmetric(vertical: 8),
child: Text(
"Sign in now",
style: TextStyle(
color: Colors.white,
fontSize: 17,
decoration: TextDecoration.underline),
),
),
),
],
),
SizedBox(
height: 50,
)
],
),
),
),
),
);
}
}
And if there is any file anyone of you want: GitHub: Chat App
Because you Haven't initialize the method

Resources