Related
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_core/firebase_core.dart';
void main() async {
//Run this first
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Smart Bin',
home: new HomePageWidget(),
);
}
}
class HomePageWidget extends StatefulWidget {
const HomePageWidget({Key key}) : super(key: key);
#override
_HomePageWidgetState createState() => _HomePageWidgetState();
}
class _HomePageWidgetState extends State<HomePageWidget> {
final scaffoldKey = GlobalKey<ScaffoldState>();
final currentBinRecord = FirebaseFirestore.instance.collection("current_bin");
#override
Widget build(BuildContext context) {
return Scaffold(
key: scaffoldKey,
appBar: AppBar(
title: Text(
'SmartBin',
),
),
body: SafeArea(
child: GestureDetector(
onTap: () => FocusScope.of(context).unfocus(),
child: Column(
mainAxisSize: MainAxisSize.max,
children: [
Expanded(
child: StreamBuilder<List<CurrentBinRecord>>(
stream: queryCurrentBinRecord(
queryBuilder: (currentBinRecord) =>
currentBinRecord.orderBy('level', descending: true),
),
builder: (context, snapshot) {
// Customize what your widget looks like when it's loading.
if (!snapshot.hasData) {
return Center(
child: SizedBox(
width: 50,
height: 50,
child: CircularProgressIndicator(),
),
);
}
List<CurrentBinRecord> listViewCurrentBinRecordList =
snapshot.data;
return ListView.builder(
padding: EdgeInsets.zero,
scrollDirection: Axis.vertical,
itemCount: listViewCurrentBinRecordList.length,
itemBuilder: (context, listViewIndex) {
final listViewCurrentBinRecord =
listViewCurrentBinRecordList[listViewIndex];
return Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text(
listViewCurrentBinRecord.area,
),
Text(
listViewCurrentBinRecord.level.toString(),
),
],
);
},
);
},
),
),
],
),
),
),
);
}
}
This is the error
First error is on:
child: StreamBuilder<List<CurrentBinRecord>>
The name 'CurrentBinRecord' isn't a type so it can't be used as a type argument.
Try correcting the name to an existing type, or defining a type named 'CurrentBinRecord'.
Second error is on:
stream: queryCurrentBinRecord
The method 'queryCurrentBinRecord' isn't defined for the type '_HomePageWidgetState'.
Try correcting the name to the name of an existing method, or defining a method named 'queryCurrentBinRecord'.
Third error is on:
List<CurrentBinRecord> listViewCurrentBinRecordList =
snapshot.data;
The name 'CurrentBinRecord' isn't a type so it can't be used as a type argument.
Try correcting the name to an existing type, or defining a type named 'CurrentBinRecord'.
These is the syntax try -
return StreamBuilder(
stream: theStreamSource, // Eg a firebase query
builder: (context, AsyncSnapshot snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(),
);
}
return ListView.builder(
itemCount: snapshot.data.documents.length,
itemBuilder: (context, int index) {
return Text(snapshot.data.documents[index]['title']);
}
);
},
);
Hope it helps.
I think the best way to use StreamBuilder is to create separate controller class that can handle all your business logic and update UI.
// your widget class
class UIClass extends StatefulWidget {
const UIClass({Key key}) : super(key: key);
#override
_UIClassState createState() => _UIClassState();
}
class _UIClassState extends State<UIClass> {
UIClassController<List<CurrentBinRecord>> _uiController;
#override
void initState() {
_uiController = UIClassController(StreamController<List<CurrentBinRecord>>());
super.initState();
}
#override
Widget build(BuildContext context) {
return Column(
children: [
Text("Hello Everyone"),
StreamBuilder<List<CurrentBinRecord>>(
stream: _uiController.uiStream,
builder: (context, snapshot) {
if(snapshot.hasError){
return ErrorWidget();
}
else if(snapshot.connectionState == ConnectionState.waiting){
return WaitingWidget();
}
else if(snapshot.hasData){
return ListView.builder(
padding: EdgeInsets.zero,
scrollDirection: Axis.vertical,
itemCount: snapshot.data.length,
itemBuilder: (context, listViewIndex) {
final listViewCurrentBinRecord =
snapshot.data[listViewIndex];
return Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text(
listViewCurrentBinRecord.area,
),
Text(
listViewCurrentBinRecord.level.toString(),
),
],
);
},
);
}
else{
return SizedBox();
}
}
),
],
);
}
#override
void dispose() {
super.dispose();
_uiController.dispose();
}
}
// controller class to handle all business logic
// you can also split it into multiple sub controllers
class UIClassController<T> {
final StreamController<T> _controller;
// If you are using this on multiple widgets then use asBroadcastStream()
Stream<T> get uiStream => _controller.stream;
UIClassController(this._controller);
void updateMyUI([dynamic params]){
T t;
// your logic //
//------------//
_controller.sink.add(t);
}
void dispose(){
_controller.close();
}
}
Code I'm Using for StreamBuilder
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import '../door/widgets/Navbar.dart';
import '../door/widgets/sidenav.dart';
import 'package:get/get.dart';
FirebaseAuth auth = FirebaseAuth.instance;
class CartPage extends StatefulWidget {
#override
_CartPageState createState() => _CartPageState();
}
class _CartPageState extends State<CartPage> {
final FirebaseFirestore fb = FirebaseFirestore.instance;
int up = 1;
bool loading = false;
final ScrollController _scrollController = ScrollController();
#override
void initState() {
super.initState();
getCartData();
}
void addMore(qty, documentID) {
int new_qty = qty + 1;
Get.snackbar('Qty! ', new_qty.toString());
String collection_name = "cart_${auth.currentUser?.email}";
FirebaseFirestore.instance
.collection(collection_name)
.doc(documentID)
.update({
'qty': new_qty,
'updated_at': Timestamp.now(),
}) // <-- Your data
.then((_) => print('Added'))
.catchError((error) => Get.snackbar('Failed!', 'Error: $error'));
}
void minusMore(qty, documentID) {
if (qty > 1) {
int new_qty = qty - 1;
String collection_name = "cart_${auth.currentUser?.email}";
FirebaseFirestore.instance
.collection(collection_name)
.doc(documentID)
.update({
'qty': new_qty,
'updated_at': Timestamp.now(),
}) // <-- Your data
.then((_) => print('Subtracted'))
.catchError((error) => Get.snackbar('Failed!', 'Error: $error'));
}
}
Stream<QuerySnapshot> getCartData() {
String collection_name = "cart_${auth.currentUser?.email}";
return FirebaseFirestore.instance
.collection(collection_name)
.orderBy("created_at", descending: false)
.snapshots();
}
final ButtonStyle style = ElevatedButton.styleFrom(
minimumSize: Size(50, 30),
backgroundColor: Color(0xFFFFB61A),
elevation: 6,
textStyle: const TextStyle(fontSize: 11),
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(20),
)));
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: Navbar.navbar(),
drawer: Sidenav.sidenav(),
body: Container(
padding: EdgeInsets.all(10.0),
child: StreamBuilder<QuerySnapshot>(
stream: getCartData(),
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
default:
if (snapshot.hasError) {
return buildText('Something Went Wrong Try later');
} else {
if (!snapshot.hasData) {
return Card(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
ListTile(
leading: ConstrainedBox(
constraints: const BoxConstraints(
minWidth: 100,
minHeight: 190,
maxWidth: 200,
maxHeight: 200,
),
child: Icon(Icons.shopping_cart, size: 45),
),
title: Text('No Food!'),
subtitle: const Text('Your cart is empty!'),
),
],
),
);
} else {
return ListView.builder(
physics: const BouncingScrollPhysics(),
shrinkWrap: true,
itemCount: snapshot.data?.docs.length,
itemBuilder: (BuildContext context, int index) {
return SizedBox(
height: 90.0,
child: Card(
elevation: 10,
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment:
CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.max,
children: <Widget>[
const SizedBox(
width: 20,
),
_buildImg('assets/logo.png', '60', '60'),
const SizedBox(
width: 14,
),
SizedBox(
width:
MediaQuery.of(context).size.width *
0.33,
child: Column(
mainAxisSize: MainAxisSize.max,
crossAxisAlignment:
CrossAxisAlignment.start,
children: <Widget>[
const SizedBox(
height: 20,
),
Text(
snapshot.data?.docs[index]
["name"],
maxLines: 2,
style: const TextStyle(
fontWeight: FontWeight.w500,
fontSize: 14)),
const SizedBox(
height: 5,
),
Text(
"₹${snapshot.data?.docs[index]["price"]}",
style: const TextStyle(
fontWeight: FontWeight.w400,
fontSize: 12)),
],
),
),
const SizedBox(
width: 10,
),
Container(
margin: const EdgeInsets.only(
top: 20.0, bottom: 10.0),
decoration: BoxDecoration(
color: const Color(0xFFFFB61A),
// color: Color(0xFF0A2031),
borderRadius:
BorderRadius.circular(17)),
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
crossAxisAlignment:
CrossAxisAlignment.end,
children: <Widget>[
SizedBox(
height: 40,
child: IconButton(
onPressed: () {
minusMore(
snapshot.data
?.docs[index]
["qty"],
snapshot
.data
?.docs[index]
.reference
.id);
},
color: Colors.white,
icon:
const Icon(Icons.remove)),
),
const SizedBox(
width: 5,
),
Container(
margin: const EdgeInsets.only(
bottom: 10.0),
child: Text(
"${snapshot.data?.docs[index]["qty"]}",
style: const TextStyle(
fontWeight:
FontWeight.w400,
color: Colors.white,
fontSize: 16)),
),
const SizedBox(
width: 5,
),
SizedBox(
height: 40,
child: IconButton(
color: Colors.white,
onPressed: () {
addMore(
snapshot.data
?.docs[index]
["qty"],
snapshot
.data
?.docs[index]
.reference
.id);
},
icon: const Icon(Icons.add)),
),
],
),
),
const SizedBox(
width: 10,
),
],
),
),
);
});
}
}
}
},
),
),
);
}
Widget buildText(String text) => Center(
child: Text(
text,
style: TextStyle(fontSize: 24, color: Colors.black),
),
);
_buildImg(img, hei, wid) {
return Container(
alignment: Alignment.center, // use aligment
child: Image.asset(
img,
height: double.parse(hei),
width: double.parse(wid),
fit: BoxFit.cover,
),
);
}
}
In the code below, I seek to make users vote only once in my Voting App.
At the moment users can vote more than once. I have created hasVoted field(a map with the UID of users and true as a value to indicate the user has voted) in the item being voted for as shown in my Firestore backend, however this does not seem to work as i want it to. What could be wrong. Does anyone here know a way around this?
Please i am new to flutter and dart so kindly forgive petty mistake that i make in posting this question
Below is my code
import 'dart:async';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:compuvote/models/finance_model.dart';
import 'package:compuvote/routes/home_page.dart';
import 'package:compuvote/routes/transitionroute.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:charts_flutter/flutter.dart' as charts;
class FinanceResult extends StatefulWidget {
#override
_FinanceResultState createState() {
return _FinanceResultState();
}
}
class _FinanceResultState extends State<FinanceResult> {
List<charts.Series<Record, String>> _seriesBarData;
List<Record> mydata;
_generateData(mydata) {
_seriesBarData = List<charts.Series<Record, String>>();
_seriesBarData.add(
charts.Series(
domainFn: (Record record, _) => record.name.toString(),
measureFn: (Record record, _) => record.totalVotes,
//colorFn: (Record record, _) => record.color,
id: 'Record',
data: mydata,
// Set a label accessor to control the text of the arc label.
labelAccessorFn: (Record row, _) => '${row.name}: ${row.totalVotes}',
colorFn: (_, __) => charts.MaterialPalette.cyan.shadeDefault,
fillColorFn: (_, __) => charts.MaterialPalette.transparent,
),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Finance Result'),
leading: IconButton(
icon: Icon(Icons.home),
onPressed: () {
Navigator.push(context, TransitionPageRoute(widget: HomePage()));
},
),
),
body: Container(
color: Colors.grey.shade100,
child: _buildBody(context),
));
}
/// ****** This code is suppose to build the body ***********/
Widget _buildBody(BuildContext context) {
return Column(
children: <Widget>[
StreamBuilder<QuerySnapshot>(
stream: Firestore.instance.collection('finance').snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Center(
child: LinearProgressIndicator(
valueColor: AlwaysStoppedAnimation(
Theme.of(context).primaryColor,
),
),
);
} else {
List<Record> finance = snapshot.data.documents
.map((documentSnapshot) =>
Record.fromMap(documentSnapshot.data))
.toList();
return _buildChart(context, finance);
}
},
),
],
);
}
Widget _buildChart(BuildContext context, List<Record> recorddata) {
mydata = recorddata;
_generateData(mydata);
return Padding(
padding: EdgeInsets.all(8.0),
child: Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height / 1.2,
child: Center(
child: Column(
children: <Widget>[
SizedBox(
height: 10.0,
),
Expanded(
child: charts.PieChart(
_seriesBarData,
animate: true,
animationDuration: Duration(seconds: 3),
//For adding labels to the chart
defaultRenderer: new charts.ArcRendererConfig(
strokeWidthPx: 2.0,
arcWidth: 100,
arcRendererDecorators: [
// <-- add this to the code
charts.ArcLabelDecorator(
labelPosition: charts.ArcLabelPosition.auto,
labelPadding: 3,
showLeaderLines: true,
insideLabelStyleSpec: charts.TextStyleSpec(
color: charts.Color.white,
fontSize: 12,
),
outsideLabelStyleSpec: charts.TextStyleSpec(
color: charts.Color.black,
fontSize: 12,
),
),
]),
),
),
Container(
width: MediaQuery.of(context).size.width / 3.5,
height: 1,
color: Colors.black38,
),
Expanded(
child: Scaffold(
backgroundColor: Colors.grey.shade100,
body: _castVote(context),
),
),
],
),
),
),
);
}
/// ****** This code is suppose to link to the Firestore collection ***********/
Widget _castVote(BuildContext context) {
return StreamBuilder<QuerySnapshot>(
stream: Firestore.instance.collection('finance').snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData)
return Center(
child: LinearProgressIndicator(
valueColor: AlwaysStoppedAnimation(
Theme.of(context).primaryColor,
),
),
);
return _buildList(context, snapshot.data.documents);
},
);
}
/// ****** This code is suppose to build the List ***********/
Widget _buildList(BuildContext context, List<DocumentSnapshot> snapshot) {
return ListView(
padding: const EdgeInsets.only(top: 20.0),
// ignore: missing_return
children: snapshot.map((data) => _buildListItem(context, data)).toList(),
);
}
/// ****** This code is suppose to build the List Items ***********/
Widget _buildListItem(BuildContext context, DocumentSnapshot data) {
final record = Record.fromSnapshot(data);
return Padding(
key: ValueKey(record.name),
padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
child: Card(
elevation: 2,
child: Container(
decoration: BoxDecoration(
border: Border.all(color: Colors.grey.shade100),
borderRadius: BorderRadius.circular(5.0),
),
child: ListTile(
title: Text(record.name),
trailing: Text(record.totalVotes.toString()),
onTap: () => {
_checkHasVoted(context, data),
}
//onTap: () => {record.reference.updateData({'votes': record.votes + 1}),
),
),
),
);
}
/// ****** This code is suppose to force users to vote only once ***********/
Widget _checkHasVoted(BuildContext context, DocumentSnapshot data) {
final record = Record.fromSnapshot(data);
StreamSubscription<DocumentSnapshot> subscription;
final DocumentReference documentReference =
Firestore.instance.collection("finance").document() as DocumentReference;
#override
void initState() {
super.initState();
subscription = documentReference.snapshots().listen((datasnapshot) {
if ((datasnapshot.data
.containsKey(FirebaseAuth.instance.currentUser()))) {
setState(() {
return Text("Sorry you have voted in this category already");
});
}
else if (!datasnapshot.data.containsKey(FirebaseAuth.instance.currentUser())){
setState(() {
record.reference.updateData({'votes':record.totalVotes + 1});
});
}
});
}
}
}
I'm Beginner to coding. I have created a Image picker in flutter, I want to use the image picker in many different pages, so I have created a separate class, but when I call the method in other pages, it just open the gallery but,it is not picking the image from gallery and displaying the picked image.There is no any error.
Kindly, help to solve the issue.
Thanks in advance
My Code:
main.dart:
import 'package:flutter/material.dart';
import 'package:project1test/healthscreen_expat.dart';
import 'package:project1test/forms/parkings.dart';
class accomodationform extends StatefulWidget {
String text;
accomodationform(String name) {
text = name;
}
#override
State<StatefulWidget> createState() {
// TODO: implement createState
return MyAppState(text);
}
}
class MyAppState extends State<accomodationform> {
Mod1 mod11 = new Mod1();
String labels;
MyAppState([String label]) {
labels = label;
}
Image1 im = Image1();
final scaffoldkey = new GlobalKey<ScaffoldState>();
final formkey = new GlobalKey<FormState>();
Widget build(BuildContext context) {
// TODO: implement build
return Scaffold(
body: new Padding(
padding: EdgeInsets.only(left: 20.0, right: 20.0, top: 20),
child: new Form(
key: formkey,
child: ListView(children: <Widget>[
mod11.user(),
]))),
);
}
}
imagepick.dart
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
class Mod1 {
var images1accom;
user() {
List<dynamic> img = List();
return Container(
margin: EdgeInsets.only(top: 20, right: 20, left: 20),
padding: EdgeInsets.only(top: 20.0),
width: double.infinity,
height: 150.0,
color: Colors.white70,
child: Center(
child: Row(
//mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
OutlineButton(
onPressed: () async {
images1accom =
await ImagePicker.pickImage(source: ImageSource.gallery);
img.add(images1accom);
},
child: Row(children: <Widget>[
Icon(Icons.camera_alt),
Text(
"Choose File",
style: TextStyle(fontSize: 12.0),
textAlign: TextAlign.end,
)
]),
borderSide: BorderSide(color: Colors.pink),
textColor: Colors.pinkAccent,
padding: EdgeInsets.all(10.0),
shape: new RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(10.0),
)),
Expanded(
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: img.length,
itemBuilder: (BuildContext c, int position) {
return (Image.file(
img[position],
fit: BoxFit.cover,
repeat: ImageRepeat.noRepeat,
));
},
),
),
],
),
),
);
}
}
Well, I think maybe it would be good for you to study object-oriented programming, dart, and how Flutter works.
Initially, I need to tell you that you simply cannot do what you are trying to do, insert widgets within classes, with separate functions, and try to instantiate it within a Stateful.
Widgets must not be instantiated, and if you want to componentize something, you must do it using a stateful or stateless class, not an ordinary class.
Your Mod class should look like this:
class ChoosePic extends StatefulWidget {
ChoosePic({Key key}) : super(key: key);
#override
_ChoosePicState createState() => _ChoosePicState();
}
class _ChoosePicState extends State<ChoosePic> {
List<dynamic> img = List();
#override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.only(top: 20, right: 20, left: 20),
padding: EdgeInsets.only(top: 20.0),
width: double.infinity,
height: 150.0,
color: Colors.white70,
child: Center(
child: Row(
//mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
OutlineButton(
onPressed: () async {
File images1accom =
await ImagePicker.pickImage(source: ImageSource.gallery);
img.add(images1accom);
setState(() {});
},
child: Row(children: <Widget>[
Icon(Icons.camera_alt),
Text(
"Choose File",
style: TextStyle(fontSize: 12.0),
textAlign: TextAlign.end,
)
]),
borderSide: BorderSide(color: Colors.pink),
textColor: Colors.pinkAccent,
padding: EdgeInsets.all(10.0),
shape: new RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(10.0),
)),
Expanded(
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: img.length,
itemBuilder: (BuildContext c, int position) {
return (Image.file(
img[position],
fit: BoxFit.cover,
repeat: ImageRepeat.noRepeat,
));
},
),
),
],
),
),
);
}
}
And you can to use it with
child: ChoosePic()
I have no idea why you are using a listview in your main class, but if it is really necessary, you would do this:
ListView(children: <Widget>[
ChoosePic(),
])
If you want the value of img, you will need a state manager for this:
Using Get (add this package to pubspec):
https://pub.dev/packages/get
Create class with shared state:
class Controller extends GetController {
static Controller get to => Get.find();
List<dynamic> img = List();
takeImage() {
File images1accom =
await ImagePicker.pickImage(source: ImageSource.gallery);
img.add(images1accom);
update(this);
}
}
// use it:
class ChoosePic extends StatefulWidget {
ChoosePic({Key key}) : super(key: key);
#override
_ChoosePicState createState() => _ChoosePicState();
}
class _ChoosePicState extends State<ChoosePic> {
#override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.only(top: 20, right: 20, left: 20),
padding: EdgeInsets.only(top: 20.0),
width: double.infinity,
height: 150.0,
color: Colors.white70,
child: Center(
child: Row(
//mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
OutlineButton(
onPressed: () async {
Controller.to.takeImage();
},
child: Row(children: <Widget>[
Icon(Icons.camera_alt),
Text(
"Choose File",
style: TextStyle(fontSize: 12.0),
textAlign: TextAlign.end,
)
]),
borderSide: BorderSide(color: Colors.pink),
textColor: Colors.pinkAccent,
padding: EdgeInsets.all(10.0),
shape: new RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(10.0),
)),
Expanded(
child: GetBuilder<Controller>(
init: Controller(),
builder: (controller) {
return ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: controller.img.length,
itemBuilder: (BuildContext c, int position) {
return (Image.file(
controller.img[position],
fit: BoxFit.cover,
repeat: ImageRepeat.noRepeat,
));
},
);
}
),
),
],
),
),
);
}
}
Now you can get the image list from anywhere in your code with:
on widget three controller.img;
GetBuilder<Controller>(
init: Controller(),
builder: (controller) {
Example:
GetBuilder<Controller>(
init: Controller(),
builder: (controller) {
return ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: controller.img.length,
itemBuilder: (BuildContext c, int position) {
return (Image.file(
controller.img[position],
fit: BoxFit.cover,
repeat: ImageRepeat.noRepeat,
));
},
);
And take it out of the widget tree with:
Controller.to.img
Note: init: Controller() can only be used once, if you need GetBuilder elsewhere, don't use it. Use, for example:
GetBuilder<Controller>(
builder: (controller) {
return ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: controller.img.length,
itemBuilder: (BuildContext c, int position) {
return (Image.file(
controller.img[position],
fit: BoxFit.cover,
repeat: ImageRepeat.noRepeat,
));
},
);
Well, I shouldn't answer that, as it qualifies as a general question, but since you are a beginner, I answered to help you, in detail. I hope you understand the basics soon, and become a great developer someday.
Welcome to Flutter!
You need to create a separate widget for Mod1 class.
MyAppState
Widget build(BuildContext context) {
return Scaffold(
body: new Padding(
padding: EdgeInsets.only(left: 20.0, right: 20.0, top: 20),
child: new Form(key: formkey, child: Mod1())),
);
}
Mod1 widget
class Mod1 extends StatefulWidget {
#override
State<StatefulWidget> createState() => Mod1State();
}
class Mod1State extends State<Mod1> {
var images1accom;
List<dynamic> img = List();
#override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.only(top: 20, right: 20, left: 20),
padding: EdgeInsets.only(top: 20.0),
width: double.infinity,
height: 150.0,
color: Colors.white70,
child: Center(
child: Row(
//mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
OutlineButton(
onPressed: () async {
images1accom =
await ImagePicker.pickImage(source: ImageSource.gallery);
setState(() {
img.add(images1accom);
});
},
child: Row(children: <Widget>[
Icon(Icons.camera_alt),
Text(
"Choose File",
style: TextStyle(fontSize: 12.0),
textAlign: TextAlign.end,
)
]),
borderSide: BorderSide(color: Colors.pink),
textColor: Colors.pinkAccent,
padding: EdgeInsets.all(10.0),
shape: new RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(10.0),
)),
Expanded(
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: img.length,
itemBuilder: (BuildContext c, int position) {
return (Image.file(
img[position],
fit: BoxFit.cover,
repeat: ImageRepeat.noRepeat,
));
},
),
),
],
),
),
);
}
}
if you want to use a method in different pages you can use Providers
Can you help me with my problem? I can create data from a textfield in my flutter app and that data goes inside my firebase collection. What I want to happen now is how can I read and display that Data inside Card with a Container child in my flutter app?
What I want is that data to be OVERLAYED or ON-TOP of the image
my code for that is here:
import 'package:flutter/material.dart';
import 'package:vmembershipofficial/Screens/discount_clicked.dart';
class DiscountCarousel extends StatelessWidget {
const DiscountCarousel({Key key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Container(
height: 220.0,
child: ListView.builder(
padding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 10.0),
shrinkWrap: true,
scrollDirection: Axis.horizontal,
itemCount: 5,
itemBuilder: (BuildContext context, int posiition) {
return Padding(
padding: EdgeInsets.symmetric(horizontal: 5.0),
child: InkWell(
onTap: () {
Navigator.push(context, MaterialPageRoute(builder: (BuildContext context) => DiscountClicked(),
),
);
},
child: Card(
child: Column(
children: <Widget>[
Container(
height: 190.0,
width: 300.0,
child: ClipRRect(
borderRadius: new BorderRadius.circular(10.0),
child: Image.network("https://images.pexels.com/photos/2529787/pexels-photo-2529787.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260", fit: BoxFit.cover)),
)
],
),),
),
);
},
)
);
}
}
I want to display the text over the images in Listview. I am able to see the Images and text but text will showing at left top corner. I want to display it on each text over the each images. Below is my code. Please help me
import 'dart:async';
import 'dart:convert';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
Future<List<Photo>> fetchPhotos(http.Client client) async {
final response = await client.get('url here');
return compute(parsePhotos, response.body);
}
// A function that will convert a response body into a List<Photo>
List<Photo> parsePhotos(String responseBody) {
final parsed = json.decode(responseBody);
return (parsed["data"]["categoryList"] as List)
.map<Photo>((json) => new Photo.fromJson(json))
.toList();
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
SystemChrome.setEnabledSystemUIOverlays([]);
return new MyHomePage();
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key}) : super(key: key);
#override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
// TODO: implement build
return new FutureBuilder<List<Photo>>(
future: fetchPhotos(new http.Client()),
builder: (context, snapshot) {
if (snapshot.hasError) print(snapshot.error);
return snapshot.hasData
? new PhotosList(photos: snapshot.data)
: new Center(child: new CircularProgressIndicator());
},
);
}
}
class PhotosList extends StatelessWidget {
final List<Photo> photos;
PhotosList({Key key, this.photos}) : super(key: key);
#override
Widget build(BuildContext context) {
return _buildBody();
}
Widget _buildBody() {
return new Stack(
children: <Widget>[
new Positioned(
child: new Container(
child: new ListView.builder(
itemCount: photos.length,
itemBuilder: (context,int){
return new Text(photos[int].title);
}
),
)
),
new ListView.builder(
itemCount: photos.length,
itemBuilder: (context,int){
return new CachedNetworkImage(imageUrl: photos[int].url);
}
),
],
);
}
}
class Photo {
final int catID;
final String title;
final String url;
final String thumbnailUrl;
final String description;
final String webstiteURL;
Photo(
{this.catID,
this.title,
this.url,
this.thumbnailUrl,
this.description,
this.webstiteURL});
factory Photo.fromJson(Map<String, dynamic> json) {
return new Photo(
catID: json['category_id'] as int,
title: json['category_name'] as String,
url: json['category_img'] as String,
thumbnailUrl: json['thumb_img'] as String,
description: json['description'] as String,
webstiteURL: json['website_url'] as String,
);
}
}
You can use a Stack widget for that:
Stack(
children: <Widget>[
yourImageWidget,
Center(child: Text("someText")),
]
)
PhotosList class:
PhotosList({Key key, this.photos}) : super(key: key);
#override
Widget build(BuildContext context) {
return _buildBody();
}
Widget _buildBody() {
return new ListView.builder(
itemCount: photos.length,
itemBuilder: (context,int){
return Stack(
children: <Widget> [
new CachedNetworkImage(imageUrl: photos[int].url),
Center(child: Text(photos[int].title)),
]
);
}
);
}
}
try this
Container(
child: Center(child: Text('test'),),
height: 190.0,
width: MediaQuery.of(context).size.width - 100.0,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(5),
color: Colors.blue,
image: DecorationImage(
image: new NetworkImage(
"https://storage.googleapis.com/gd-wagtail-prod-assets/original_images/MDA2018_inline_03.jpg"
),
fit: BoxFit.fill
)
),
),
I find this worked a bit better and you don't need the Center widget:
Stack(
alignment: Alignment.center,
children: <Widget>[
yourImageWidget,
Text("someText"),
]
)
Just want to add a small example of Stack Widget
return Scaffold(
appBar: AppBar(
title: Text("Text Over Image"),
),
body: Center(
child: Stack(
children: <Widget>[
Container(
alignment: Alignment.center,
child: Image.network(
'https://cdn.pixabay.com/photo/2018/07/11/21/51/toast-3532016_1280.jpg',
height: 250,
width: double.infinity,
fit: BoxFit.cover,
),
),
Container(
alignment: Alignment.center,
child: Text(
'Text Message',
style: TextStyle(color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 22.0),
)),
],
),
),
);
Output:
You can read more in my article on medium.com
try this
Card(
elevation: 4,
margin: EdgeInsets.fromLTRB(0.0, 4.0, 4.0, 4.0),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(4.0),
),
shadowColor: Colors.white,
color: Colors.white70,
child: Stack(children: <Widget>[
Center(
child: Image(
image: NetworkImage(ApiContent.PREF_IMAGES_PATH +
_listMomentListModel[index].filePath),
),
),
Column(mainAxisAlignment: MainAxisAlignment.end, children: [
Container(
width: double.infinity,
color: Colors.white,
padding: EdgeInsets.fromLTRB(8.0, 8.0, 8.0, 8.0),
child: Text(
_listMomentListModel[index].title,
maxLines: 5,
textAlign: TextAlign.center,
)),
]),
]),
);
to set text bottom
mainAxisAlignment: MainAxisAlignment.end,
to set text top
mainAxisAlignment: MainAxisAlignment.start,
to set text center
mainAxisAlignment: MainAxisAlignment.center,
Example of Text over background-image using Stack.
body: SafeArea(
child: Stack(
children:[
Container(
decoration: const BoxDecoration(
image: DecorationImage(
image: AssetImage("Assets/splash_images/splash.png",),fit: BoxFit.cover,
),
),
),
Column(
children: const [
Center(
child: Text("Text is Here ",style:TextStyle(fontSize: 20),)
,
)
],
)
]),
)
**
Click Here For Output
**