i am making a wallpaper app in flutter, i made wallpaper grids and i want to implement native ads in this GridView but i am not getting how to?
Can someone please help me to implement, i have tried a lot of things but none of them worked for me
This is what i want -
Here i want to implement -
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import '../views/wallpaper.dart';
import '../../core/utils/models/response.dart';
class WallpaperList extends StatefulWidget {
final List<Post> posts;
final ThemeData themeData;
WallpaperList({#required this.posts, #required this.themeData});
#override
_WallpaperListState createState() => _WallpaperListState();
}
class _WallpaperListState extends State<WallpaperList> {
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
return widget.posts.length == 0
? SizedBox(
height: 200,
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(16.0),
child: Icon(FontAwesomeIcons.sadCry,
size: 30, color: widget.themeData.accentColor),
),
Text(
'Seems like what you are looking for, is empty.',
style: widget.themeData.textTheme.body2,
)
],
),
)
: wallpaperGrid(widget.posts);
}
Widget wallpaperGrid(List<Post> list) {
return GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2, childAspectRatio: 0.7),
padding: const EdgeInsets.all(0),
itemCount: list.length,
shrinkWrap: true,
physics: ScrollPhysics(),
scrollDirection: Axis.vertical,
itemBuilder: (BuildContext context, int index) {
return Card(
elevation: 10,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15.0),
),
child: GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => WallpaperPage(
heroId: 'popular${list[index].name}',
posts: list,
index: index,
)));
},
child: Hero(
tag: 'popular${list[index].name}',
child: SizedBox(
width: double.infinity,
height: 300,
child: ClipRRect(
borderRadius: BorderRadius.circular(15.0),
child: CachedNetworkImage(
errorWidget: (context, url, error) => Container(
width: double.infinity,
height: double.infinity,
child: Center(
child: Icon(
Icons.error,
color: widget.themeData.accentColor,
),
),
),
fit: BoxFit.cover,
placeholder: (context, url) => Center(
child: Container(
width: double.infinity,
height: double.infinity,
color: widget.themeData.primaryColorDark,
child: Center(
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation(
widget.themeData.accentColor),
))),
),
imageUrl:
list[index].preview.images[0].resolutions.length <= 3
? widget
.posts[index]
.preview
.images[0]
.resolutions[list[index]
.preview
.images[0]
.resolutions
.length -
1]
.url
.replaceAll('amp;', '')
: list[index]
.preview
.images[0]
.resolutions[3]
.url
.replaceAll('amp;', ''),
),
),
),
),
),
);
},
);
}
}
Please help, any help would be appreciated
Below is the Example for Implement Admob Native ads in Staggered GridView in flutter
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:flutter_native_admob/flutter_native_admob.dart';
import 'package:flutter_native_admob/native_admob_controller.dart';
import 'package:cached_network_image/cached_network_image.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
var _list = List<IMageClass>();
static const _adUnitID = "ca-app-pub-3940256099942544/8135179316";
final _nativeAdController = NativeAdmobController();
double _height = 0;
#override
void initState() {
super.initState();
_getData();
}
Widget Images(int index) {
return CachedNetworkImage(
imageUrl: _list[index].images,
placeholder: (context, string) {
return Center(
child: CupertinoActivityIndicator(),
);
},
imageBuilder: (context, imageProvider) => Container(
decoration: BoxDecoration(
image: DecorationImage(
image: imageProvider,
fit: BoxFit.cover,
),
),
),
errorWidget: (context, url, error) => Icon(Icons.error),
);
}
List<String> imageList = [
'https://images.unsplash.com/photo-1515886657613-9f3515b0c78f',
'https://images.unsplash.com/photo-1529626455594-4ff0802cfb7e',
'https://images.unsplash.com/photo-1513956589380-bad6acb9b9d4',
'https://images.unsplash.com/photo-1521577352947-9bb58764b69a',
'https://images.unsplash.com/photo-1488161628813-04466f872be2',
'https://images.unsplash.com/photo-1501196354995-cbb51c65aaea',
'https://images.unsplash.com/photo-1515886657613-9f3515b0c78f',
'https://images.unsplash.com/photo-1529626455594-4ff0802cfb7e',
'https://images.unsplash.com/photo-1513956589380-bad6acb9b9d4',
'https://images.unsplash.com/photo-1521577352947-9bb58764b69a',
'https://images.unsplash.com/photo-1488161628813-04466f872be2',
'https://images.unsplash.com/photo-1501196354995-cbb51c65aaea',
'https://images.unsplash.com/photo-1515886657613-9f3515b0c78f',
'https://images.unsplash.com/photo-1529626455594-4ff0802cfb7e',
'https://images.unsplash.com/photo-1513956589380-bad6acb9b9d4',
'https://images.unsplash.com/photo-1521577352947-9bb58764b69a',
'https://images.unsplash.com/photo-1488161628813-04466f872be2',
'https://images.unsplash.com/photo-1501196354995-cbb51c65aaea',
'https://images.unsplash.com/photo-1515886657613-9f3515b0c78f',
'https://images.unsplash.com/photo-1529626455594-4ff0802cfb7e',
'https://images.unsplash.com/photo-1513956589380-bad6acb9b9d4',
'https://images.unsplash.com/photo-1521577352947-9bb58764b69a',
'https://images.unsplash.com/photo-1488161628813-04466f872be2',
'https://images.unsplash.com/photo-1501196354995-cbb51c65aaea',
'https://images.unsplash.com/photo-1515886657613-9f3515b0c78f',
'https://images.unsplash.com/photo-1529626455594-4ff0802cfb7e',
'https://images.unsplash.com/photo-1513956589380-bad6acb9b9d4',
'https://images.unsplash.com/photo-1521577352947-9bb58764b69a',
'https://images.unsplash.com/photo-1488161628813-04466f872be2',
'https://images.unsplash.com/photo-1501196354995-cbb51c65aaea',
];
void _getData() {
for (int i = 0; i < imageList.length; i++) {
var image = IMageClass();
if (i != 0) {
if (i % 4 == 3) {
image.type = "GoogleAd";
} else {
image.type = "";
image.images = imageList[i];
}
_list.add(image);
} else {
image.type = "";
image.images = imageList[i];
_list.add(image);
}
}
}
Widget _getAdContainer() {
return Container(
height: 250,
child: NativeAdmob(
// Your ad unit id
adUnitID: "ca-app-pub-3940256099942544/8135179316",
controller: _nativeAdController,
type: NativeAdmobType.banner,
),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
margin: EdgeInsets.all(12),
child: StaggeredGridView.countBuilder(
crossAxisSpacing: 3.0,
mainAxisSpacing: 3.0,
// controller: scrollController,
itemCount: _list.length,
physics: ScrollPhysics(),
itemBuilder: (context, index) {
if (_list[index].type != "GoogleAd")
return Images(index);
else
return _getAdContainer();
},
crossAxisCount: 2,
staggeredTileBuilder: (int index) {
if (_list[index].type != "GoogleAd")
return StaggeredTile.count(1, 1);
else
return StaggeredTile.count(2, 1);
// return StaggeredTile.count(1, 1);
},
)),
);
}
}
class IMageClass {
String images;
String type;
}
Related
While I am typing the message it encodes it into white but when I have sent it, it turns to black which is the same with the response that I have been receiving. Kindly help me how will i change it to white.
import 'package:dialog_flowtter/dialog_flowtter.dart';
import 'package:flutter/material.dart';
import 'Messages.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'QuickTropa',
theme: ThemeData(
primaryColor: Color(0XFFf7c59f),
),
home: Home(),
);
}
}
class Home extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
late DialogFlowtter dialogFlowtter;
final TextEditingController _controller = TextEditingController();
List<Map<String, dynamic>> messages = [];
#override
void initState() {
DialogFlowtter.fromFile().then((instance) => dialogFlowtter = instance);
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('QuickTropa'),
backgroundColor: Color(0XFF087830),
),
body: Container(
child: Column(
children: [
Expanded(child:
MessagesScreen(
messages:
messages)),
Container(
padding: EdgeInsets.symmetric(
horizontal: 14,
vertical: 8
),
color: Color(0XFF087830),
child: Row(
children: [
Expanded(child:
TextField(
controller: _controller,
style: TextStyle(color: Colors.white),
)),
IconButton(
onPressed: () {
sendMessage(_controller.text);
_controller.clear();
},
color: Colors.white ,
icon: Icon(Icons.send))
],
),
)
],
),
),
);
}
sendMessage(String text) async {
if (text.isEmpty) {
print('Message is empty');
} else {
setState(() {
addMessage(Message(
text: DialogText(text: [text])), true);
});
DetectIntentResponse response = await dialogFlowtter.detectIntent(
queryInput: QueryInput(text: TextInput(text: text)));
if (response.message == null) return;
setState(() {
addMessage(response.message!);
});
}
}
addMessage(Message message, [bool isUserMessage = false]) {
messages.add({
'message': message,
'isUserMessage': isUserMessage
});
}
}
import 'package:dialog_flowtter/dialog_flowtter.dart';
import 'package:flutter/material.dart';
class MessagesScreen extends StatefulWidget {
final List messages;
const MessagesScreen({Key? key, required this.messages}) : super(key: key);
#override
State<MessagesScreen> createState() => _MessagesScreenState();
}
class _MessagesState extends State<MessagesScreen> {
#override
Widget build(BuildContext context) {
return const Placeholder();
}
}
class _MessagesScreenState extends State<MessagesScreen> {
#override
Widget build(BuildContext context) {
var w = MediaQuery.of(context).size.width;
return ListView.separated(
itemBuilder: (context, index) {
return Container(
margin: EdgeInsets.all(10),
child: Row(
mainAxisAlignment: widget.messages[index]['isUserMessage']
? MainAxisAlignment.end
: MainAxisAlignment.start,
children: [
Container(
padding: EdgeInsets.symmetric(vertical: 14, horizontal: 14),
decoration: BoxDecoration(
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(
20,
),
topRight: Radius.circular(20),
bottomRight: Radius.circular(
widget.messages[index]['isUserMessage'] ? 0 : 20),
topLeft: Radius.circular(
widget.messages[index]['isUserMessage'] ? 20 : 0),
),
color: widget.messages[index]['isUserMessage']
? Color(0XFF087830)
: Color(0XFF087830).withOpacity(0.8)),
constraints: BoxConstraints(maxWidth: w * 2 / 3),
child:
Text(widget.messages[index]['message'].text.text[0])),
],
),
);
},
separatorBuilder: (_, i) => Padding(padding: EdgeInsets.only(top: 10)),
itemCount: widget.messages.length);
}
}
I tried putting Color:Colors.white isnide the box decoration but of course it wouldn't let me. I can't think anymore where to put it.
Try this
Text(widget.messages[index]['message'].text.text[0],
style:TextStyle(color:Colors.white,)
)
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,
),
);
}
}
I am using flutter river pods for this project. I want to change the API call when pressing on the second and third tab. I.e make the JSON API link dynamic. How can I do that?
Each widget is in its different file
Here is my code
main.dart
void main() {
WidgetsFlutterBinding.ensureInitialized();
runApp(ProviderScope(child: MyApp()));
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: true,
home: HomeView(),
);
}
}
Home_views.dart
class HomeView extends ConsumerWidget {
const HomeView({Key? key}) : super(key: key);
#override
Widget build(BuildContext context, WidgetRef ref) {
TabController controller;
final ModelView = ref.watch(getFutureData);
return Consumer(
builder: (context, WidgetRef ref, _) {
return TabBarWidget;
}
);
}
}
Data_model.dart
class DataModel {
const DataModel({
required this.id,
required this.joke,
required this.categories,
});
final int id;
final String joke;
final String categories;
}
data_controllers.dart
final getFutureData = ChangeNotifierProvider<GetApiDATA>((ref) => GetApiDATA());
class GetApiDATA extends ChangeNotifier{
List<DataModel> ListOfDataModels = [];
GetApiDATA(){
getDataApi();
}
Future getDataApi() async {
ListOfDataModels = [];
try{
http.Response ApiResponse = await http.get(Uri.parse("https://v2.jokeapi.dev/joke/Programming?type=single&contains=joke&amount=10"));
if (ApiResponse.statusCode == 200) {
final body = jsonDecode(ApiResponse.body) as Map<String, dynamic>;
if (body['error'] == false) {
final jokes = body['jokes'];
for (final joke in jokes) {
final jokeMap = joke as Map<String, dynamic>;
print("jokeText is ${jokeMap['joke']}");
final id = jokeMap['id'] as int;
final jokeText = jokeMap['joke'] as String;
final categories = jokeMap['category'] as String;
ListOfDataModels.add(DataModel(id: id, joke: jokeText, categories: categories));
}
print("Length is ${ListOfDataModels.length}");
notifyListeners();
}
}
}
catch(e)
{
print(e.toString());
}
}
}
TabBarWidget.dart
import 'package:assignment_moe/Controllers/data_controllers.dart';
import 'package:assignment_moe/Widgets/TabViewWidget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
Widget TabBarWidget = Consumer(
builder: (context, WidgetRef ref, _) {
final ModelView = ref.watch(getFutureData);
return MaterialApp(
home: DefaultTabController(
length: 3,
child: Scaffold(
backgroundColor: Color(0XffF7F7F7),
appBar: AppBar(
backgroundColor: Color(0xff1B9C8F),
title: Text('Jokes API'),
),
body: Column(
children: [
Container(
margin: const EdgeInsets.only(top: 30, left: 10,right: 10),
height: 35,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15),
color: Colors.white,
),
child: TabBar(
indicator: BoxDecoration(
color: Color(0xff1B9C8F),
borderRadius: BorderRadius.all(Radius.circular(10)),
),
labelColor: Colors.white,
unselectedLabelColor: Color(0xff1B9C8F),
tabs: [
Tab(
text: 'Programming',
),
Tab(
text: 'Dark',
),
Tab(
text: 'Spooky',
),
],
),
),
Expanded(
child: TabBarView(
children: [
TabViewWidget,
TabViewWidget,
TabViewWidget,
],
),
),
],
),
),
),
);
}
);
TabViewWidget.dart
import 'package:assignment_moe/Controllers/data_controllers.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
Widget TabViewWidget = Consumer (
builder: (context, WidgetRef ref, _) {
final ModelView = ref.watch(getFutureData);
return ModelView.ListOfDataModels.isEmpty ?
Center(child: CircularProgressIndicator(),) :
ListView.builder(
itemCount: ModelView.ListOfDataModels.length,
itemBuilder: (context, index) =>
Container(
margin: EdgeInsets.only(top: 20,left: 20,right: 20),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(15),
color: Colors.white,
),
child: Padding(
padding: const EdgeInsets.all(10.0),
child: ListTile(
title: Text(ModelView.ListOfDataModels[index].categories
),
subtitle: Padding(
padding: const EdgeInsets.only(top: 10),
child: Text(ModelView.ListOfDataModels[index].joke),
),
leading: Container(
alignment: Alignment.center,
width: 35,
height: 35,
decoration: BoxDecoration(
color: Color(0xff1B9C8F),
borderRadius: BorderRadius.circular(20)),
child: Text(
ModelView.ListOfDataModels[index].id.toString(),
style: TextStyle(color: Colors.white),
),
),
),
),
),
);
}
);
Below is the screen shot
ANy help would be appreciated
How can I click item in StaggeredGridView in Flutter?
I want to add Navigator and send link photo to another screen.
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: "Flutter Staggered View",
home: MyHome(),
);
}
}
class MyHome extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: StaggeredGridView.countBuilder(
crossAxisCount: 4,
itemCount: 15,
itemBuilder: (BuildContext context, int index) => new Container(
height: 120.0,
width: 120.0,
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage('https://picsum.photos/500/500?random=$index') ,
fit: BoxFit.fill,
),
shape: BoxShape.rectangle,
),
),
staggeredTileBuilder: (int index) =>
new StaggeredTile.count(2, index.isEven ? 3 : 2),
mainAxisSpacing: 4.0,
crossAxisSpacing: 4.0,
),
),
);
}
}
You can wrap the widget that is returned by the itemBuilder with a widget that can handle tap events, such as a GestureDetector or an InkWell:
itemBuilder: (BuildContext context, int index) => GestureDetector(
onTap: () {
// call Navigator here
},
child: Container(
height: 120.0,
width: 120.0,
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage('https://picsum.photos/500/500?random=$index'),
fit: BoxFit.fill,
),
shape: BoxShape.rectangle,
),
),
),
More information on GestureDetector or InkWell can be found in the docs
You can check the below code. You need to use GestureDetector. Then push it in another class. please check my answer for details.
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: "Flutter Staggered View",
home: MyHome(),
);
}
}
class MyHome extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: StaggeredGridView.countBuilder(
crossAxisCount: 4,
itemCount: 15,
itemBuilder: (BuildContext context, int index) => GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
details("https://picsum.photos/500/500?random=$index")),
);
},
child: new Container(
height: 120.0,
width: 120.0,
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage(
'https://picsum.photos/500/500?random=$index'),
fit: BoxFit.fill,
),
shape: BoxShape.rectangle,
),
),
),
staggeredTileBuilder: (int index) =>
new StaggeredTile.count(2, index.isEven ? 3 : 2),
mainAxisSpacing: 4.0,
crossAxisSpacing: 4.0,
),
),
);
}
}
class details extends StatelessWidget {
details(this.image);
String image;
#override
Widget build(BuildContext context) {
return Container(
width: 200,
height: 200,
child: Image.network(image),
);
}
}
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});
});
}
});
}
}
}