Addpage optimierung, button wird ausgeblendet auf der profil page

This commit is contained in:
2023-04-28 00:08:05 +02:00
parent 6834e34b6a
commit 097f2744be
3 changed files with 143 additions and 252 deletions
+93 -56
View File
@@ -9,7 +9,7 @@ import 'package:cloud_firestore/cloud_firestore.dart';
class AddScreen extends StatefulWidget { class AddScreen extends StatefulWidget {
final int initialIndex; final int initialIndex;
AddScreen({required this.initialIndex}); const AddScreen({super.key, required this.initialIndex});
@override @override
_AddScreenState createState() => _AddScreenState(); _AddScreenState createState() => _AddScreenState();
@@ -23,14 +23,16 @@ class _AddScreenState extends State<AddScreen> {
bool _uploading = false; bool _uploading = false;
int _selectedIndex = 0; int _selectedIndex = 0;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
_selectedIndex = widget.initialIndex; _selectedIndex = widget.initialIndex;
} }
Future<void> _getImage(ImageSource source) async { Future<void> _getImage(ImageSource source) async {
final pickedFile = await ImagePicker().getImage(source: source); final pickedFile = await ImagePicker().pickImage(source: source);
if (pickedFile != null) { if (pickedFile != null) {
setState(() { setState(() {
@@ -38,45 +40,19 @@ class _AddScreenState extends State<AddScreen> {
}); });
} }
} }
Future<void> addNewElementToFirestore(String title, String description, File imageFile) async { Future<void> addNewElementToFirestore(String title, String description, File imageFile) async {
// Zunächst das Bild in Firebase Storage speichern String collectionName;
if (_selectedIndex == 0) {
collectionName = "CitizensForum";
// Das neue Element in der Firestore-Sammlung "Issues" speichern } else if (_selectedIndex == 1) {
if(_selectedIndex == 0) collectionName = "News";
{ } else {
Reference ref = FirebaseStorage.instance.ref().child("CitizensForum/${DateTime.now().toString()}"); collectionName = "Issues";
UploadTask uploadTask = ref.putFile(imageFile);
String imageUrl = await (await uploadTask).ref.getDownloadURL();
await FirebaseFirestore.instance.collection("CitizensForum").add({
"title": title,
"description": description,
"imageUrl": imageUrl,
"createdDate": DateTime.now(),
});
} }
else if(_selectedIndex == 1)
{
Reference ref = FirebaseStorage.instance.ref().child("News/${DateTime.now().toString()}");
UploadTask uploadTask = ref.putFile(imageFile);
String imageUrl = await (await uploadTask).ref.getDownloadURL();
await FirebaseFirestore.instance.collection("News").add({ String imageUrl = await uploadImageToFirebaseStorage(imageFile, collectionName);
"title": title,
"description": description, await FirebaseFirestore.instance.collection(collectionName).add({
"imageUrl": imageUrl,
"createdDate": DateTime.now(),
});
}
else
{
Reference ref = FirebaseStorage.instance.ref().child("Issues/${DateTime.now().toString()}");
UploadTask uploadTask = ref.putFile(imageFile);
String imageUrl = await (await uploadTask).ref.getDownloadURL();
await FirebaseFirestore.instance.collection("Issues").add({
"title": title, "title": title,
"description": description, "description": description,
"imageUrl": imageUrl, "imageUrl": imageUrl,
@@ -84,19 +60,33 @@ class _AddScreenState extends State<AddScreen> {
}); });
} }
Future<String> uploadImageToFirebaseStorage(File imageFile, String collectionName) async {
Reference ref = FirebaseStorage.instance.ref().child("$collectionName/${DateTime.now().toString()}");
UploadTask uploadTask = ref.putFile(imageFile);
return await (await uploadTask).ref.getDownloadURL();
} }
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
String appBarTitle = '';
if (_selectedIndex == 0) {
appBarTitle = 'Neue BürgerForum Information';
} else if (_selectedIndex == 1) {
appBarTitle = 'Neue Neuigkeit';
} else if (_selectedIndex == 2) {
appBarTitle = 'Neuer Mängel';
}
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
title: Text('Neues Element hinzufügen'), title: Text(appBarTitle),
actions: [ actions: [
Padding( Padding(
padding: const EdgeInsets.only(right: 8.0), padding: const EdgeInsets.only(right: 8.0),
child: IconButton( child: IconButton(
icon: Icon(Icons.refresh), icon: const Icon(Icons.refresh),
onPressed: () { onPressed: () {
_titleController.clear(); _titleController.clear();
_descriptionController.clear(); _descriptionController.clear();
@@ -109,14 +99,17 @@ class _AddScreenState extends State<AddScreen> {
Padding( Padding(
padding: const EdgeInsets.only(right: 8.0), padding: const EdgeInsets.only(right: 8.0),
child: IconButton( child: IconButton(
icon: Icon(Icons.check), icon: const Icon(Icons.check),
onPressed: () async { onPressed: () async {
if (_formKey.currentState!.validate() && _imageFile != null && !_uploading) { if (_formKey.currentState!.validate() && _imageFile != null &&
!_uploading) {
setState(() { setState(() {
_uploading = true; _uploading = true;
}); });
try { try {
await addNewElementToFirestore(_titleController.text, _descriptionController.text, _imageFile!); await addNewElementToFirestore(
_titleController.text, _descriptionController.text,
_imageFile!);
Navigator.pop(context); Navigator.pop(context);
} catch (e) { } catch (e) {
print(e); print(e);
@@ -128,7 +121,6 @@ class _AddScreenState extends State<AddScreen> {
} }
} }
}, },
), ),
), ),
], ],
@@ -156,7 +148,7 @@ class _AddScreenState extends State<AddScreen> {
return null; return null;
}, },
), ),
SizedBox(height: 16.0), const SizedBox(height: 16.0),
TextFormField( TextFormField(
decoration: InputDecoration( decoration: InputDecoration(
labelText: 'Beschreibung', labelText: 'Beschreibung',
@@ -174,11 +166,11 @@ class _AddScreenState extends State<AddScreen> {
return null; return null;
}, },
), ),
SizedBox(height: 16.0), const SizedBox(height: 16.0),
_imageFile != null _imageFile != null
? Image.file(_imageFile!) ? Image.file(_imageFile!)
: Container( : Container(
height: 150.0, height: 200.0,
decoration: BoxDecoration( decoration: BoxDecoration(
color: Colors.grey[200], color: Colors.grey[200],
borderRadius: BorderRadius.circular(16.0), borderRadius: BorderRadius.circular(16.0),
@@ -188,25 +180,68 @@ class _AddScreenState extends State<AddScreen> {
onPressed: () { onPressed: () {
showModalBottomSheet( showModalBottomSheet(
context: context, context: context,
builder: (context) => Column( builder: (context) =>
Column(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
ListTile( Container(
leading: Icon(Icons.photo_library), height: 60,
title: Text('Galerie auswählen'), padding: const EdgeInsets.symmetric(
horizontal: 16),
child: Row(
mainAxisAlignment: MainAxisAlignment
.spaceBetween,
children: [
const Text(
'Bild hinzufügen',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
IconButton(
icon: const Icon(Icons.close),
onPressed: () {
Navigator.pop(context);
},
),
],
),
),
Center(
child: Container(
height: 80,
child: ListTile(
leading: const Icon(
Icons.photo_library, size: 40),
title: const Text(
'Galerie auswählen',
style: TextStyle(fontSize: 20),
),
onTap: () { onTap: () {
Navigator.pop(context); Navigator.pop(context);
_getImage(ImageSource.gallery); _getImage(ImageSource.gallery);
}, // },
),
),
),
Center(
child: Container(
height: 80,
child: ListTile(
leading: const Icon(
Icons.camera_alt, size: 40),
title: const Text(
'Kamera verwenden',
style: TextStyle(fontSize: 20),
), ),
ListTile(
leading: Icon(Icons.camera_alt),
title: Text('Kamera verwenden'),
onTap: () { onTap: () {
Navigator.pop(context); Navigator.pop(context);
_getImage(ImageSource.camera); _getImage(ImageSource.camera);
}, },
), ),
),
),
], ],
), ),
); );
@@ -214,7 +249,9 @@ class _AddScreenState extends State<AddScreen> {
child: Text( child: Text(
'Bild hinzufügen', 'Bild hinzufügen',
style: TextStyle( style: TextStyle(
color: Theme.of(context).primaryColor, color: Theme
.of(context)
.primaryColor,
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
), ),
), ),
+6 -154
View File
@@ -26,7 +26,8 @@ class UserDefinedItem extends StatelessWidget {
Navigator.push( Navigator.push(
context, context,
MaterialPageRoute( MaterialPageRoute(
builder: (context) => DetailPage( builder: (context) =>
DetailPage(
title: title, title: title,
datum: datum, datum: datum,
description: description, description: description,
@@ -59,7 +60,8 @@ class UserDefinedItem extends StatelessWidget {
overflow: TextOverflow.ellipsis, overflow: TextOverflow.ellipsis,
style: const TextStyle( style: const TextStyle(
fontSize: 20, fontSize: 20,
fontWeight: FontWeight.bold// beliebige Schriftgröße fontWeight: FontWeight
.bold // beliebige Schriftgröße
), ),
), ),
), ),
@@ -73,7 +75,8 @@ class UserDefinedItem extends StatelessWidget {
), ),
), ),
Padding( Padding(
padding: const EdgeInsets.all(8.0), // feste Höhe für 2 Zeilen padding: const EdgeInsets.all(8.0),
// feste Höhe für 2 Zeilen
child: Text( child: Text(
description, description,
maxLines: 3, maxLines: 3,
@@ -264,57 +267,6 @@ class _CitizensForumState extends State<CitizensForum> {
itemBuilder: (BuildContext context, int index) { itemBuilder: (BuildContext context, int index) {
final Map<String, dynamic> data = documents[index].data(); final Map<String, dynamic> data = documents[index].data();
final DateTime createdDate = data['createdDate'].toDate(); final DateTime createdDate = data['createdDate'].toDate();
final formattedDate = DateFormat.yMd().format(createdDate);
return UserDefinedItem(
title: data['title'] ?? '',
datum: formattedDate,
description: data['description'] ?? '',
image: Image.network((data['imageUrl'])),
);
},
);
}
},
);
}
}
/*class NewsList extends StatefulWidget {
const NewsList({Key? key}) : super(key: key);
@override
_NewsListState createState() => _NewsListState();
}
class _NewsListState extends State<NewsList> {
final FirebaseFirestore firestore = FirebaseFirestore.instance;
late Stream<QuerySnapshot> newsStream;
@override
void initState() {
super.initState();
newsStream = firestore.collection('News').snapshots();
}
@override
Widget build(BuildContext context) {
return StreamBuilder<QuerySnapshot>(
stream: newsStream,
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
}
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return const Text('Loading...');
default:
final List<QueryDocumentSnapshot> documents = snapshot.data!.docs;
return ListView.builder(
itemCount: documents.length,
itemBuilder: (BuildContext context, int index) {
final Map<String, dynamic> data = documents[index].data()! as Map<String, dynamic>;
final DateTime createdDate = data['createdDate'].toDate();
final formattedDate = DateFormat('dd.MM.yyyy').format(createdDate); final formattedDate = DateFormat('dd.MM.yyyy').format(createdDate);
return UserDefinedItem( return UserDefinedItem(
title: data['title'] ?? '', title: data['title'] ?? '',
@@ -329,103 +281,3 @@ class _NewsListState extends State<NewsList> {
); );
} }
} }
class IssueList extends StatefulWidget {
const IssueList({Key? key}) : super(key: key);
@override
_IssueListState createState() => _IssueListState();
}
class _IssueListState extends State<IssueList> {
final FirebaseFirestore firestore = FirebaseFirestore.instance;
late Stream<QuerySnapshot> issueStream;
@override
void initState() {
super.initState();
issueStream = firestore.collection('Issues').snapshots();
}
@override
Widget build(BuildContext context) {
return StreamBuilder<QuerySnapshot>(
stream: issueStream,
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
}
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return const Text('Loading...');
default:
final List<QueryDocumentSnapshot> documents = snapshot.data!.docs;
return ListView.builder(
itemCount: documents.length,
itemBuilder: (BuildContext context, int index) {
final Map<String, dynamic> data = documents[index].data()! as Map<String, dynamic>;
final DateTime createdDate = data['createdDate'].toDate();
final formattedDate = DateFormat('dd.MM.yyyy').format(createdDate);
return UserDefinedItem(
title: data['title'] ?? '',
datum: formattedDate,
description: data['description'] ?? '',
image: Image.network((data['imageUrl'])),
);
},
);
}
},
);
}
}
class CitizensForum extends StatefulWidget {
const CitizensForum({Key? key}) : super(key: key);
@override
_CitizensForumState createState() => _CitizensForumState();
}
class _CitizensForumState extends State<CitizensForum> {
final FirebaseFirestore firestore = FirebaseFirestore.instance;
late Stream<QuerySnapshot<Map<String, dynamic>>> citizenStream;
@override
void initState() {
super.initState();
citizenStream = firestore.collection('CitizensForum').snapshots();
}
@override
Widget build(BuildContext context) {
return StreamBuilder<QuerySnapshot<Map<String, dynamic>>>(
stream: citizenStream,
builder: (BuildContext context, AsyncSnapshot<QuerySnapshot<Map<String, dynamic>>> snapshot) {
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
}
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return const Text('Loading...');
default:
final List<QueryDocumentSnapshot<Map<String, dynamic>>> documents = snapshot.data!.docs;
return ListView.builder(
itemCount: documents.length,
itemBuilder: (BuildContext context, int index) {
final Map<String, dynamic> data = documents[index].data();
final DateTime createdDate = data['createdDate'].toDate();
final formattedDate = DateFormat.yMd().format(createdDate);
return UserDefinedItem(
title: data['title'] ?? '',
datum: formattedDate,
description: data['description'] ?? '',
image: Image.network((data['imageUrl'])),
);
},
);
}
},
);
}
}*/
+3 -1
View File
@@ -57,7 +57,9 @@ class _MyHomePageState extends State<MyHomePage> {
body: Center( body: Center(
child: widgetOptions.elementAt(_selectedIndex), child: widgetOptions.elementAt(_selectedIndex),
), ),
floatingActionButton: FloatingActionButton( floatingActionButton: _selectedIndex == 3 // Wenn der ausgewählte Index 3 ist, also auf dem Profil-Widget
? null // Zeigt keinen Button an
: FloatingActionButton(
onPressed: () { onPressed: () {
Navigator.push( Navigator.push(
context, context,