[![enter image description here][1]][1]
I need to do it like this here:
[1]: https://i.stack.imgur.com/bNdZ3.png
But I can't do it. I tried some stuff but it doesn't work. Here is my main.dart below. I created the showImage method for showing image, I also applied it by Image.network(url); code but it didn't work,so I commented it.
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_core/firebase_core.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.red,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
var url;
void _incrementCounter() {
setState(() {
_counter++;
});
}
void showImage() async {
final ref = FirebaseStorage.instance.ref().child('erkekyuz');
// no need of the file extension, the name will do fine.
url = await ref.getDownloadURL();
print(url);
}
Widget _buildListItem(BuildContext context, DocumentSnapshot document) {
String mezunD;
if (document.data()['mezunDurumu'] == false) {
mezunD = "mezun değil";
}
if (document.data()['mezunDurumu'] == true) {
mezunD = "mezun değil";
}
var listTile = ListTile(
title: Column(
children: [
Expanded(
child: Text(
"Ad Soyad: " + document.data()['adSoyad'],
),
),
Expanded(
child: Text(
"Yaş: " + document.data()['yas'].toString(),
),
),
Expanded(
child: Text(
"Doğum Tarihi: " + document.data()['dogumTarihi'],
),
),
Expanded(
child: Text("Mezun Durumu: " + mezunD),
),
//Image.network(url),
//this didn't work somehow.
],
),
);
return listTile;
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Öğrenci Durumu"),
),
body: StreamBuilder(
stream: FirebaseFirestore.instance.collection('tablolar').snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) return const Text('Loading...');
return ListView.builder(
itemExtent: 100.0,
itemCount: snapshot.data.documents.length,
itemBuilder: (context, index) =>
_buildListItem(context, snapshot.data.documents[index]),
);
}),
);
}
}
Is your url variable showing any value?
Call your showImage() method like this to load image.
#override
void initState() {
super.initState();
showImage();
}
for showing images you can use :https://pub.dev/packages/cached_network_image
Related
I am unable to assign my one class to another even though I have imported the lib for them. I am following a course . In this I will fetch the orders from firebase and showing the orderscreen.
Orderscreen(where i am getting the error):
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/orders.dart' show Orders;
import '../widgets/app_drawer.dart';
import 'package:shop_app/Widgets/OrderItem.dart';
class OrdersScreen extends StatelessWidget {
static const routeName = '/orders';
#override
Widget build(BuildContext context) {
print('building orders');
// final orderData = Provider.of<Orders>(context);
return Scaffold(
appBar: AppBar(
title: Text('Your Orders'),
),
drawer: AppDrawer(),
body: FutureBuilder(
future: Provider.of<Orders>(context, listen: false).fetchandSetOrders(),
builder: (ctx, dataSnapshot) {
if (dataSnapshot.connectionState == ConnectionState.waiting) {
return Center(child: CircularProgressIndicator());
} else {
if (dataSnapshot.error != null) {
// ...
// Do error handling stuff
return Center(
child: Text('An error occurred!'),
);
} else {
return Consumer<Orders>(
builder: (ctx, orderData, child) => ListView.builder(
itemCount: orderData.orders.length,
itemBuilder: (ctx, i) => OrderItem(orderData.orders[i])//getting error here
),
);
}
}
},
),
);
}
}
My orderitem class :
class OrderItem extends StatefulWidget {
final ord.OrderItem order;
OrderItem(this.order);
#override
State<OrderItem> createState() => _OrderItemState();
}
class _OrderItemState extends State<OrderItem> {
var _expanded = false;
#override
Widget build(BuildContext context) {
return Card(
margin: EdgeInsets.all(10),
child: Column(
children: [
ListTile(
title: Text('\$${widget.order.amount}'),
subtitle: Text(
DateFormat('dd/MM/yyyy/ hh:mm').format(widget.order.dateTime),
),
trailing: IconButton(
icon: Icon(_expanded
? Icons.expand_less_rounded
: Icons.expand_more_rounded),
onPressed: () {
setState(() {
_expanded = !_expanded;
});
},
)),
if (_expanded)
Container(
height: min(widget.order.products.length * 20.0 + 100, 180),
child: ListView(
children: widget.order.products
.map((prod) => Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(prod.title),
Text('${prod.quanitity}x \$${prod.price}')
],
))
.toList()
//min function will give min of two functions , if expanded is true then this will take place
,
),
),
],
),
);
}
}
My orders class:
class OrderItem {
final String id;
final double amount;
final List<CartItem> products;
final DateTime dateTime;
OrderItem(this.id, this.amount, this.products, this.dateTime);
}
class Orders with ChangeNotifier {
List<OrderItem> _orders = [];
List<OrderItem> get orders {
return [..._orders];
}}
Thanks guys for all your help. it would be helpful if you can explain why i got this error as I am a novice to flutter
ide ss
Your widgets file name and data class name are same.It has same class name.Make data class name and widgets name different.It will solve the issue
Change the file name and widget name is working
Plugin Use:
provider: ^6.0.2
OrdersScreen (Order_screen.dart)
import 'package:flutter/material.dart';
import 'package:order_item_proj/OrderItem.dart';
import 'package:order_item_proj/Orders.dart' show Orders;
import 'package:provider/provider.dart';
class OrdersScreen extends StatelessWidget {
static const routeName = '/orders';
#override
Widget build(BuildContext context) {
print('building orders');
// final orderData = Provider.of<Orders>(context);
return Scaffold(
appBar: AppBar(
title: Text('Your Orders'),
),
body: FutureBuilder(
future: Provider.of<Orders>(context, listen: false).fetchandSetOrders(),
builder: (ctx, dataSnapshot) {
if (dataSnapshot.connectionState == ConnectionState.waiting) {
return Center(child: CircularProgressIndicator());
} else {
if (dataSnapshot.error != null) {
// ...
// Do error handling stuff
return Center(
child: Text('An error occurred!'),
);
} else {
return Consumer<Orders>(
builder: (ctx, orderData, child) =>
ListView.builder(itemCount: orderData.orders.length, itemBuilder: (ctx, i) => OrderItemWidget(orderData.orders[i])),
);
}
}
},
),
);
}
}
OrderItem Widget (OrderItem.dart)
import 'package:flutter/material.dart';
import 'package:order_item_proj/Orders.dart' as ord;
class OrderItemWidget extends StatefulWidget {
final ord.OrderItem order;
OrderItemWidget(this.order);
#override
State<OrderItemWidget> createState() => _OrderItemWidgetState();
}
class _OrderItemWidgetState extends State<OrderItemWidget> {
var _expanded = false;
#override
Widget build(BuildContext context) {
return Card(
margin: EdgeInsets.all(10),
child: Column(
children: [
ListTile(
title: Text('\$${widget.order.amount}'),
subtitle: Text(""),
trailing: IconButton(
icon: Icon(_expanded ? Icons.expand_less_rounded : Icons.expand_more_rounded),
onPressed: () {
setState(() {
_expanded = !_expanded;
});
},
)),
if (_expanded)
Container(
child: ListView(
children: widget.order.products
.map((prod) => Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text("title"),
],
))
.toList()
//min function will give min of two functions , if expanded is true then this will take place
,
),
),
],
),
);
}
}
OrderItem Class (Orders.dart)
import 'package:flutter/cupertino.dart';
class OrderItem {
final String id;
final double amount;
final List<String> products;
final DateTime dateTime;
OrderItem(this.id, this.amount, this.products, this.dateTime);
}
class Orders with ChangeNotifier {
List<OrderItem> _orders = [];
List<OrderItem> get orders {
return [..._orders];
}
fetchandSetOrders() {}
}
I have a Flutter application running through VS Code which does simple authentication using Firebase. Following is my full program.
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:provider/provider.dart';
import 'package:fireauth_starter/views/home_view.dart';
import 'views/login_page_view.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(FireAuthStarter());
}
class FireAuthStarter extends StatelessWidget {
//final Future<FirebaseApp> _initialisation = Firebase.initializeApp();
#override
Widget build(BuildContext context) {
//
return Provider<FirebaseAuth>(
create: (context) => FirebaseAuth.instance,
child: MaterialApp(
title: 'Firebase Authentication',
home: LandingPage(),
),
);
}
}
class LandingPage extends StatelessWidget {
const LandingPage();
#override
Widget build(BuildContext context) {
final firebaseAuth = Provider.of<FirebaseAuth>(context);
return StreamBuilder<User>(
stream: firebaseAuth.authStateChanges(),
builder: (context, AsyncSnapshot<User> snapshot) {
print(snapshot.connectionState.toString());
if (snapshot.connectionState == ConnectionState.active) {
//final bool signedIn = snapshot.hasData;
User user = snapshot.data;
return user == null ? LoginPageView() : HomeView();
//return signedIn ? DashBoard() : FirstView();
} else {
return Scaffold(
body: Center(
child: CircularProgressIndicator(),
),
);
}
});
}
}
class LoginPageView extends StatelessWidget {
#override
Widget build(BuildContext context) {
final firebaseAuth = Provider.of<FirebaseAuth>(context);
return MaterialApp(
home: Center(
child: Container(
child: TextButton(
child: Text('Sign In'),
onPressed: () {
firebaseAuth.signInWithEmailAndPassword(
email: 'myemail#email.com',
password: '1234567',
);
},
),
),
),
);
}
}
class HomeView extends StatelessWidget {
#override
Widget build(BuildContext context) {
final firebaseAuth = Provider.of<FirebaseAuth>(context);
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Home View'),
actions: [
TextButton(
child: Text('Sign Out'),
style: ButtonStyle(
foregroundColor: MaterialStateProperty.all<Color>(Colors.white),
),
onPressed: () {
firebaseAuth.signOut();
},
),
],
),
body: Center(
child: Container(child: Text('Home View content')),
),
),
);
}
}
The application works as expected but when I use hot reload or hot restart, app get stuck in Progress Indicator because the snapshot.connectionState returns 'ConnectionState.waiting'
https://api.flutter.dev/flutter/widgets/ConnectionState-class.html states waiting: indicating that the asynchronous operation has begun, typically with the data being null.
I though the hot restart will reset all the states and app will perform as initial load. But it doesn't. What am I missing in this?
When I run the code below, all I am getting now is.
I copied this code from another this post. This seems to work, prior to the last code I had, but I still am getting no success on retrieving any data. I tried the other things in the same post but I had no luck.
The method 'data' was called on null.
Receiver: null
Tried calling: data()
void main() {
runApp(myApp());
}
class myApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: FirstRoute(title: 'First Route'),
);
}
}
class FirstRoute extends StatefulWidget {
FirstRoute({Key key, this.title}) : super(key: key);
final String title;
#override
_FirstRouteState createState() => _FirstRouteState();
}
class _FirstRouteState extends State<FirstRoute> {
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("test"),
),
body: FutureBuilder(
future: getData(),
builder: (context, AsyncSnapshot<DocumentSnapshot> snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
return Column(
children: [
Container(
height: 27,
child: Text(
"Name: ${snapshot.data.data()['Name']}",
overflow: TextOverflow.fade,
style: TextStyle(fontSize: 20),
),
),
],
);
} else if (snapshot.connectionState == ConnectionState.none) {
return Text("No data");
}
return CircularProgressIndicator();
},
));
}
Future<DocumentSnapshot> getData() async {
await Firebase.initializeApp();
return await FirebaseFirestore.instance
.collection("test")
.doc()
.get();
}
}
On the firestore website it says that there are some reads and there's also snapshots listeners active, but the error still persists.
Any recommendations and tips would be great. Thanks!
I am trying to convert the boilerplate Flutter example into a web application and store the time of each click in Firestore. The program can login and the counter got incremented at each click. But it can't write to Firestore (checked via Firebase Console). Grateful if anyone can point out where I have done wrong, or pointer to the right approach. This is the code:
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
#override
void _incrementCounter() {
setState(() async {
Firestore.instance.collection("click").add(
{
"time" : DateTime.now(),
});
_counter++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('DEMO')
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
class AuthService {
//Handle Authentication
handleAuth() {
FirebaseAuth.instance
.signInWithEmailAndPassword(
email: 'xxxxxxxx#gmail.com', password: 'xxxxxxxx');
return StreamBuilder(
stream: FirebaseAuth.instance.onAuthStateChanged,
builder: (context, snapshot) {
if (snapshot.hasData) {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => MyHomePage()),
);
;
} else {
return Text('Login failed');
}
},
);
}
}
I'm working on a Flutter project and using Sqflite database. I've managed to save data in db. Now I am trying to get list of all records from database based on table name and display them in "ListView.builder".
database_helper.dart
Future<List> getAllRecords(String dbTable) async {
var dbClient = await db;
var result = await dbClient.rawQuery("SELECT * FROM $dbTable");
return result.toList();
}
employees_list.dart
import 'package:flutter/material.dart';
import 'package:flutter_with_db_single_helper/helpers/database_helper.dart';
var db = new DatabaseHelper();
Future<List> _users = db.getAllRecords("tabEmployee"); // CALLS FUTURE
class EmployeesListScreen extends StatefulWidget {
#override
_EmployeesListScreenState createState() => _EmployeesListScreenState();
}
class _EmployeesListScreenState extends State<EmployeesListScreen> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('List Of Employees'),
),
body: ListView.builder(
// itemCount: _users.length,
itemBuilder: (_, int position) {
return Card(
child: ListTile(
title:
Text("Employee Name: "), // EMPLOYEE NAME TO BE DISPLAYED HERE
),
);
},
),
);
}
}
Where did I go wrong? What can I do to display all my db table records in list?
You could use a FutureBuilder to get and display your data :
class _EmployeesListScreenState extends State<EmployeesListScreen> {
var db = new DatabaseHelper(); // CALLS FUTURE
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('List Of Employees'),
),
body: FutureBuilder<List>(
future: db.getAllRecords("tabEmployee"),
initialData: List(),
builder: (context, snapshot) {
return snapshot.hasData
? ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (_, int position) {
final item = snapshot.data[position];
//get your item data here ...
return Card(
child: ListTile(
title: Text(
"Employee Name: " + snapshot.data[position].row[1]),
),
);
},
)
: Center(
child: CircularProgressIndicator(),
);
},
),
);
}
}
This might not be correct code, since I've not tested this, but this is how list view builder works and try using async await. Cleans up code quite a bit!
import 'package:flutter/material.dart';
import 'package:flutter_with_db_single_helper/helpers/database_helper.dart'
class EmployeesListScreen extends StatefulWidget {
#override
_EmployeesListScreenState createState() => _EmployeesListScreenState();
}
class _EmployeesListScreenState extends State<EmployeesListScreen> {
List<String> _records;
#override
initState(){
super.initState();
}
Future<void> _getRecords() async {
var res = await db.getAllRecords("tabEmployee");
setState((){
_records = res;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('List Of Employees'),
),
body: _records==null ? Container():ListView.builder(
itemCount: _records.length,
itemBuilder: (_, int position) {
return Card(
child: ListTile(
title:
Text("Employee Name: ", _records[position]),
),
);
},
),
);
}
}
Or you can use a future builder, as the other answer shows. :)