Flutter error : Got the error on length and map - flutter

I Got the error on length and map after upgrading flutter.
And the same code is running in the old project.
when I print only snapshot.data then data is not showing.
class _TabPageState extends State<TabPage> {
var response;
var medicineSubCategoryApi;
#override
void initState() {
super.initState();
fetchData(widget.medicineCatUniqId);
}
fetchData(var medicineCatUniqId) async {
var api = Uri.parse($baseUrl/productSubCatApi.php?a2rTokenKey=$a2rTokenKey&pcat=$medicineCatUniqId');
response = await http.get(
api,
);
print("medicineCatApiLnk " + api.toString());
print("medicineCat" + response.body);
medicineSubCategoryApi = jsonDecode(response.body);
print("medicineCatString" + medicineSubCategoryApi.toString());
return medicineSubCategoryApi;
// setState(() {});
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: FutureBuilder(
future: fetchData(medicineSubCategoryApi),
// initialData: medicineSubCategoryApi,
builder: (context, snapshot) {
if (snapshot.hasData) {
print(snapshot.data.length.toString());
print(snapshot.data.toString());
// API data will be stored as snapshot.data
return DefaultTabController(
length: snapshot.data.length,
child: Scaffold(
appBar: AppBar(
title: const Text('Tabbed AppBar'),
bottom: TabBar(
isScrollable: true,
tabs: snapshot.data
.map<Widget>((choice) => Tab(
text: choice['psubCatName'],
// icon: Icon(choice),
))
.toList(),
),
),
body: TabBarView(
physics: NeverScrollableScrollPhysics(),
children: snapshot.data.map<Widget>((choice) {
return Padding(
padding: const EdgeInsets.all(20.0),
child: ChoicePage(
choice: choice,
),
);
}).toList(),
),
),
);
} else if (snapshot.hasError) {
return Text('Error');
} else {
return Text('Loading');
}
}),
);
}
}
class ChoicePage extends StatelessWidget {
const ChoicePage({Key? key, this.choice}) : super(key: key);
final choice;
#override
Widget build(BuildContext context) {
final TextStyle? textStyle = Theme.of(context).textTheme.headline4;
return Card(
color: Colors.white,
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Text(
choice['psubCatName'],
style: textStyle,
),
],
),
),
);
}
}
when I print This thing I got then coming error.
class _TabPageState extends State<TabPage> {
var response;
var medicineSubCategoryApi;
#override
void initState() {
super.initState();
// for loading
fetchData(widget.medicineCatUniqId);
}
fetchData(var medicineCatUniqId) async {
var api = Uri.parse('$baseUrl/productSubCatApi.php?a2rTokenKey=$a2rTokenKey&pcat=$medicineCatUniqId');
response = await http.get(
api,
);
print("medicineCatApiLnk " + api.toString());
print("medicineCat" + response.body);
// in double quotes drink is key value of json
medicineSubCategoryApi = jsonDecode(response.body);
print("medicineCatString" + medicineSubCategoryApi.toString());
return medicineSubCategoryApi;
// setState(() {});
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: FutureBuilder(
future: fetchData(medicineSubCategoryApi),
// initialData: medicineSubCategoryApi,
builder: (context, snapshot) {
if (snapshot.hasData) {
print(snapshot.data.length.toString());
print(snapshot.data.toString());
return Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(snapshot.data.length.toString()),
Text(snapshot.data.toString()),
],
);
// API data will be stored as snapshot.data
}).toList(),
),
),
);
} else if (snapshot.hasError) {
return Text('Error');
} else {
return Text('Loading');
}
}),
);
}
}

try this
print(snapshot.data!.length!.toString());
print(snapshot.data!.toString());
it can solve the problem if you were not using Flutter 2.0 before

Related

Fetch Data From database and show on listView.builder?

I want to fetch data from the Database and want to show all the records of some columns by using listView.builder in flutter code .How I can do this ??
I want to fetch data from the Database and want to show all the records of some columns by using listView.builder in flutter code .How I can do this ??
static Future<List> getData() async {
final db = await SQLHelper.db();
var data= (await db.rawQuery('select column1,column2,column3,column4 From table'));
return data.toList();
}
import 'package:flutter/material.dart';
import 'package:test_02/dbHelper.dart';
class showOutlets extends StatefulWidget {
#override
State<showOutlets> createState() => showOutletsState();
}
class showOutletsState extends State<showOutlets> {
num age = -1;
String birthDate = "";
var data ;
List<dynamic> list = [SQLHelper.getOutletsData()];
bool _isLoading = false;
void _showFullRecord() async {
data = await SQLHelper.getOutletsData( );
setState(() {
data =data;
_isLoading = false;
});
}
static var boldStyle= const TextStyle(
fontWeight: FontWeight.bold,
);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('User Data' ),
),
body: _isLoading? const Center(
child: CircularProgressIndicator(),
)
: ListView.builder(
itemCount: list.length,
itemBuilder: (context, index ) => Card(
color: Colors.orangeAccent,
// color: Colors.orange[200],
margin: const EdgeInsets.all(15),
child: Column(
children: [
const Text("USER INFORMATION ",
style: TextStyle(
fontSize: 20.0,
),),
// Text('NAME:${data}'), // how can I show the data on the screen
],
),
)
)
);
}
Create state variable future,
late final future = YourDBClass.getData();
Now use FutureBuilder
FutureBuilder(
future: future,
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.builder(...loaded data on snapshot.dat..a);
}
if (snapshot.hasError) return Text("error");
return CircularProgressIndicator();
},
),
More about FutureBuilder
I didn't understand what you really want. but here is an example of how you can get data from database and show them on the screen.
import 'package:flutter/material.dart';
void main() {
runApp(showOutlets());
}
class showOutlets extends StatefulWidget {
#override
State<showOutlets> createState() => showOutletsState();
}
class showOutletsState extends State<showOutlets> {
num age = -1;
String birthDate = "";
bool _isLoading = true;
List<dynamic> dataList;
_getData() async {
dataList = await getDataFromDatabase(); // get data here
_isLoading = false;
}
#override
void initState() {
_getData();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('User Data'),
),
body: _isLoading
? const Center(
child: CircularProgressIndicator(),
)
: ListView.builder(
itemCount: dataList.length,
itemBuilder: (context, index) => Card(
// Design your card.
color: Colors.orangeAccent,
margin: const EdgeInsets.all(15),
child: Column(
children: [
const Text(
"USER INFORMATION ",
style: TextStyle(
fontSize: 20.0,
),
),
],
),
),
),
);
}
}

_TypeError (type 'Future<dynamic>' is not a subtype of type 'Widget')

am trying to call the user from data (am using firebase as database)
the profile page not working for more understanding check the other issue i posted last day :
FirebaseException ([cloud_firestore/unavailable] The service is currently unavailable , and how to solve it
import 'package:cached_network_image/cached_network_image.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:yumor/models/progress.dart';
import 'package:yumor/models/user_model.dart';
class profile extends StatefulWidget {
const profile({Key? key,required this.userProfile}) : super(key: key);
final String? userProfile;
#override
State<profile> createState() => _profileState();
}
class _profileState extends State<profile> {
final userRef = FirebaseFirestore.instance.collection('users');
buildprofileheader() async{
final doc=await userRef.doc(widget.userProfile).get();
if(doc.exists){
var data=doc.data();
}
return FutureBuilder(future:FirebaseFirestore.instance.collection('users').doc(userRef.id).get(),
builder: ((context, snapshot) {
if(!snapshot.hasData){
return CircularProgress();
}
UserModel user=UserModel.fromMap(Map);
return Padding(padding:EdgeInsets.all(16.0),
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Icon(Icons.account_circle, size: 90,)
],
),
Container(
alignment: Alignment.center,
padding: EdgeInsets.all(12.0),
child: Text(
user.Username as String,
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize:16.0,
),
),
),
],
),
);
}),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text(
"Profile",
),
),
body: ListView(children: <Widget>[
buildprofileheader(), // the error shows in this line <=======
]));
}
}
Your buildprofileheader return type is Future<Widget> but it should be Widget in order to use in ListView, so you need to use an other FutureBuilder to get userRef. So just wrap your current FutureBuilder with an other one.
As for the logic part, you can simplify the logic for future method something like
Future<UserModel?> getData() async {
try{
final userRef = FirebaseFirestore.instance.collection('users');
final doc = await userRef.doc(widget.userProfile).get();
if (doc.exists) {
var data = doc.data(); // not sure about this use case
} else {
return null;
}
final data = await FirebaseFirestore.instance
.collection('users')
.doc(userRef.id)
.get();
if (data.exists) {
UserModel user = UserModel.fromMap(data);
return user;
}
} catch(e){ }
}
Create a state variable for future method , and use like
late final future = getData();
Widget buildprofileheader() {
return FutureBuilder<UserModel?>(
future: future,
builder: ((context, snapshot) {
if (!snapshot.hasData) {
return CircularProgress();
}
return Padding(....
class _profileState extends State<profile> {
Future<UserModel?> getData() async {
final userRef = FirebaseFirestore.instance.collection('users');
final doc = await userRef.doc(widget.userProfile).get();
if (doc.exists) {
var data = doc.data(); // not sure about this use case
} else {
return null;
}
final data = await FirebaseFirestore.instance
.collection('users')
.doc(userRef.id)
.get();
if (data.exists) {
UserModel user = UserModel.fromMap(data);
return user;
}
}
late final future = getData();
Widget buildprofileheader() {
return FutureBuilder<UserModel?>(
future: future,
builder: ((context, snapshot) {
if (!snapshot.hasData) {
return CircularProgressIndicator();
}
return Padding(
padding: EdgeInsets.all(16.0),
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Icon(
Icons.account_circle,
size: 90,
)
],
),
Container(
alignment: Alignment.center,
padding: EdgeInsets.all(12.0),
child: Text(
user.Username as String,
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 16.0,
),
),
),
],
),
);
}),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text(
"Profile",
),
),
body: ListView(children: <Widget>[
buildprofileheader(),
]));
}
}

I am trying to fetch collection from shopify admin api with rest api in flutter

I am Using flutter with http package. in my code CircularProgressIndicator() is running and is not showing any error
here is my http request code
import 'package:http/http.dart' as http;
import 'dart:convert';`
class Collections {
Future<List> getAllCollections() async {
var headers = {
'Content-Type': 'application/json',
'X-Shopify-Access-Token': '{token}',
};
var url = Uri.parse(
'https://{shop}.myshopify.com/admin/api/2022-07/collections.json');
try {
var res = await http.get(url, headers: headers);
print(res);
if (res.statusCode == 200) {
return jsonDecode(res.body);
} else {
return Future.error("Server Error");
}
} catch (SocketException) {
return Future.error("Error Fetching Data");
}
}
}
and here I created the object of this class and using it.
class ProCategories extends StatefulWidget {
const ProCategories({Key? key}) : super(key: key);
#override
State<ProCategories> createState() => _ProCategoriesState();
}
class _ProCategoriesState extends State<ProCategories> {
Collections collections = Collections();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Categories"),
centerTitle: true,
foregroundColor: Colors.black,
backgroundColor: Colors.white,
),
body: Container(
margin: EdgeInsets.only(top: 8.0),
child: FutureBuilder<List>(
builder: (context, snapshot) {
if (snapshot.hasData) {
if (snapshot.data?.length == 0) {
return Center(
child: Text("0 Collections"),
);
}
return ListView.builder(
itemCount: snapshot.data?.length,
itemBuilder: (context, index) {
return Card(
child: ListTile(
title: Row(
children: [
Expanded(
child: Container(
child: Text(
snapshot.data![index]['collections']['edges']
['node']['title'],
style: TextStyle(
fontSize: 25,
fontWeight: FontWeight.bold),
),
),
),
],
),
),
);
});
} else if (snapshot.hasError) {
return Center(
child: Text(snapshot.error.toString()),
);
} else {
return Center(
child: CircularProgressIndicator(),
);
}
},
),
),
);
}
}
Add future to FutureBuilder.
late Future<List> getAllCollections;
#override
void initState() {
super.initState();
getAllCollections = collections.getAllCollections();
}
#override
Widget build(BuildContext context) {
return Scaffold(
...
body: Container(
margin: EdgeInsets.only(top: 8.0),
child: FutureBuilder<List>(
future: getAllCollections,
builder: (context, snapshot) {
...
},
),
),
);
}
See Fetch data from the internet for the full example.

How to hide or show widget built inside FutureBuilder based on daynamic changes

Am able to show and hide the widget i want but it keeps flickering or rebuilding its self every time.
i just want to show the the capture icon button when the compass degree reaches 190 degree
this is my main widget
late List<CameraDescription> cameras;
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
cameras = await availableCameras();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: CameraApp(),
);
}
}
class CameraApp extends StatefulWidget {
#override
_CameraAppState createState() => _CameraAppState();
}
class _CameraAppState extends State<CameraApp> {
String? imagePath;
XFile? imageFile;
late CameraController controller;
late Future<void> _initializeControllerFuture;
int? angleResult;
bool showCaptureButton = false;
String? getLocation;
bool k = false;
void getAngleFromCompass(newResult) {
WidgetsBinding.instance!.addPostFrameCallback((_) {
setState(() {
angleResult = newResult;
});
});
}
void getLocationRes(newResult) {
getLocation = newResult;
}
#override
void initState() {
super.initState();
controller = CameraController(
// Get a specific camera from the list of available cameras.
cameras[0],
// Define the resolution to use.
ResolutionPreset.high,
imageFormatGroup: ImageFormatGroup.yuv420,
);
_initializeControllerFuture = controller.initialize().then((value) {
setState(() {});
});
}
#override
void dispose() {
controller.dispose();
super.dispose();
}
void _captureImage() async {
await takePicture().then((filePath) {
if (mounted) {
setState(() {
imagePath = filePath;
});
}
});
}
Widget cameraWidget(context) {
var camera = controller.value;
final size = MediaQuery.of(context).size;
var scale = size.aspectRatio * camera.aspectRatio;
if (scale < 1) scale = 1 / scale;
return Transform.scale(
scale: scale,
child: Center(
child: CameraPreview(controller),
),
);
}
#override
Widget build(BuildContext context) {
if (!controller.value.isInitialized) {
return Container();
}
theCompassApp(getAngleFromCompass) keeps flikering here
return Scaffold(
body: FutureBuilder(
future: _initializeControllerFuture,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
return Stack(
children: [
cameraWidget(context),
Align(
alignment: Alignment.topCenter,
child: LocationApp(getLocationRes),
),
Align(
child: CompassApp(getAngleFromCompass),
),
Align(
alignment: Alignment.bottomCenter,
child: Container(
color: Color(0xAA333639),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
children: [
angleResult == 190 ? IconButton(
onPressed: () => _captureImage(),
iconSize: 40,
icon: Icon(
Icons.camera_alt,
color: Colors.white,
),
) : Text(''),
],
),
),
)
],
);
} else {
return Center(
child: CircularProgressIndicator(),
);
}
},
),
);
}
Compass App Widget
class CompassApp extends StatefulWidget {
final getAngleValue;
CompassApp(this.getAngleValue);
#override
_CompassAppState createState() => _CompassAppState();
}
class _CompassAppState extends State<CompassApp> {
bool _hasPermissions = false;
#override
void initState() {
super.initState();
_fetchPermissionStatus();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
backgroundColor: Colors.transparent,
body: Builder(builder: (context) {
if (_hasPermissions) {
return Column(
children: <Widget>[
Expanded(child: _buildCompass()),
],
);
} else {
return Text('');
}
}),
),
);
}
Widget _buildCompass() {
return StreamBuilder<CompassEvent>(
stream: FlutterCompass.events,
builder: (context, snapshot) {
if (snapshot.hasError) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 30),
child: Text('Error reading heading not support'),
);
}
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(),
);
}
double? direction = snapshot.data!.heading;
int ang = direction!.round();
Compass angle passed to main widget here
widget.getAngleValue(ang);
if (direction.isNaN)
return Center(
child: Text("Device does not have sensors !"),
);
return Material(
color: Colors.transparent,
child: Column(
children: [
RotatedBox(
quarterTurns: 1,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 41),
child: Text(
'$ang',
style: TextStyle(
fontSize: 50,
color: Colors.white,
backgroundColor: Colors.black26),
),
),
),
],
),
);
},
);
}
void _fetchPermissionStatus() {
Permission.locationWhenInUse.status.then((status) {
if (mounted) {
setState(() => _hasPermissions = status == PermissionStatus.granted);
}
});
}
}
Have you tried Visibility or Opacity?
Visibility
Visibility(
visible: true, //false for invisible
child: Text('I am visible'),
),
Opacity
Opacity(
opacity: 1.0, //0.0 for invisible
child: Text('I am visible'),
),

my snapshot doesn't have the data in futurebuilder

pls, help if you can .i am trying to fetch some data from rest api .but on the getTreadingWallpapers() method it shows me full json data. but whenever I print snapshot.hasError on else condition.. it shows me false. it means the snapshot has not error..but why i am not getting the data in my future builder. no error showing , how can i solve this problem
class _FrontPageState extends State<FrontPage> {
Future<List<RecentPage>> recentPage;
RecentPage recentPagee;
bool isLoading = true;
List<RecentPage> wallpapers = new List();
Future<List<RecentPage>> getTrendingWallpapers() async {
// final url ="http://wallpaper.pkappstudio.info/api/api.php?action=get_recent";
String url = 'http://wallpaper.pkappstudio.info/api/api.php?action=get_recent';
final response =
await Http.get(url, headers: {"Accept": "application/json"});
if (response.statusCode == 200) {
final Map = jsonDecode(response.body);
print("${response.body}");
isLoading = false;
final recentPaget = recentPageFromJson(response.body).asMap();
recentPaget.entries.forEach((element) => wallpapers.add(element.value));
return wallpapers;
} else {
throw Exception('Failed to load post');
}
}
#override
void initState() {
// TODO: implement initState
recentPage = getTrendingWallpapers();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(title: brandName(),elevation: 0.0,),
body: FutureBuilder(
future: recentPage,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.none &&
snapshot.hasData == null) {
print('project snapshot data is: ${snapshot.data}');
return isLoading? Center(child: Container(child: Text("container"),)):Center(child: Container(child: Text("csdsdontainer"),));
}
if(snapshot.hasData){
return isLoading? Center(child: CircularProgressIndicator()):ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index){
return Container(
padding: EdgeInsets.symmetric(horizontal: 16),
child: GridView.count(
shrinkWrap: true,
crossAxisCount: 2,
physics: ClampingScrollPhysics(),
childAspectRatio: 0.6,
mainAxisSpacing: 6.0,
crossAxisSpacing: 6.0,
children: wallpapers.map((wallpapers){
return GridTile(child: GestureDetector(
onTap: (){
// Navigator.push(context, MaterialPageRoute(builder: (context)=>ImageView(
// imageUrl: wallpapers.src.potrait,
// )));
},
child: Container(
child: ClipRRect(
borderRadius: BorderRadius.circular(10),
child:Image.network(snapshot.data.imageUrl, fit: BoxFit.cover,),
),
),
));
}).toList(),
),
);
},
);
} else return Container(child: Text("${snapshot.hasError}"),);
},
)
);
}
}
You can copy paste run full code below
Step 1: You do not need isLoading , you can directly use check ConnectionState
Step 2: You do not need to declare List<RecentPage> wallpapers, snapshot.data already keep this
code snippet
builder: (context, AsyncSnapshot<List<RecentPage>> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text('none');
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
case ConnectionState.active:
return Text('');
case ConnectionState.done:
if (snapshot.hasError) {
return Text(
'${snapshot.error}',
style: TextStyle(color: Colors.red),
);
} else {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
return Container(
padding: EdgeInsets.symmetric(horizontal: 16),
child: GridView.count(
shrinkWrap: true,
crossAxisCount: 2,
physics: ClampingScrollPhysics(),
childAspectRatio: 0.6,
mainAxisSpacing: 6.0,
crossAxisSpacing: 6.0,
children: snapshot.data.map((wallpapers) {
return GridTile(
child: GestureDetector(
onTap: () {
// Navigator.push(context, MaterialPageRoute(builder: (context)=>ImageView(
// imageUrl: wallpapers.src.potrait,
// )));
},
child: Container(
child: ClipRRect(
borderRadius: BorderRadius.circular(10),
child: Image.network(
wallpapers.imageUrl,
fit: BoxFit.cover,
working demo
full code
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
List<RecentPage> recentPageFromJson(String str) =>
List<RecentPage>.from(json.decode(str).map((x) => RecentPage.fromJson(x)));
String recentPageToJson(List<RecentPage> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class RecentPage {
RecentPage({
this.no,
this.imageId,
this.imageUpload,
this.imageUrl,
this.type,
this.viewCount,
this.downloadCount,
this.featured,
this.tags,
this.categoryId,
this.categoryName,
});
int no;
String imageId;
String imageUpload;
String imageUrl;
Type type;
String viewCount;
String downloadCount;
Featured featured;
String tags;
String categoryId;
String categoryName;
factory RecentPage.fromJson(Map<String, dynamic> json) => RecentPage(
no: json["no"],
imageId: json["image_id"],
imageUpload: json["image_upload"],
imageUrl: json["image_url"],
type: typeValues.map[json["type"]],
viewCount: json["view_count"],
downloadCount: json["download_count"],
featured: featuredValues.map[json["featured"]],
tags: json["tags"],
categoryId: json["category_id"],
categoryName: json["category_name"],
);
Map<String, dynamic> toJson() => {
"no": no,
"image_id": imageId,
"image_upload": imageUpload,
"image_url": imageUrl,
"type": typeValues.reverse[type],
"view_count": viewCount,
"download_count": downloadCount,
"featured": featuredValues.reverse[featured],
"tags": tags,
"category_id": categoryId,
"category_name": categoryName,
};
}
enum Featured { YES, NO }
final featuredValues = EnumValues({"no": Featured.NO, "yes": Featured.YES});
enum Type { UPLOAD }
final typeValues = EnumValues({"upload": Type.UPLOAD});
class EnumValues<T> {
Map<String, T> map;
Map<T, String> reverseMap;
EnumValues(this.map);
Map<T, String> get reverse {
if (reverseMap == null) {
reverseMap = map.map((k, v) => new MapEntry(v, k));
}
return reverseMap;
}
}
class FrontPage extends StatefulWidget {
#override
_FrontPageState createState() => _FrontPageState();
}
class _FrontPageState extends State<FrontPage> {
Future<List<RecentPage>> recentPage;
RecentPage recentPagee;
bool isLoading = true;
List<RecentPage> wallpapers = new List();
Future<List<RecentPage>> getTrendingWallpapers() async {
// final url ="http://wallpaper.pkappstudio.info/api/api.php?action=get_recent";
String url =
'http://wallpaper.pkappstudio.info/api/api.php?action=get_recent';
final response =
await http.get(url, headers: {"Accept": "application/json"});
if (response.statusCode == 200) {
final Map = jsonDecode(response.body);
print("${response.body}");
isLoading = false;
final recentPaget = recentPageFromJson(response.body).asMap();
recentPaget.entries.forEach((element) => wallpapers.add(element.value));
return wallpapers;
} else {
throw Exception('Failed to load post');
}
}
#override
void initState() {
// TODO: implement initState
recentPage = getTrendingWallpapers();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: Text("brandName()"),
elevation: 0.0,
),
body: FutureBuilder(
future: recentPage,
builder: (context, AsyncSnapshot<List<RecentPage>> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text('none');
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
case ConnectionState.active:
return Text('');
case ConnectionState.done:
if (snapshot.hasError) {
return Text(
'${snapshot.error}',
style: TextStyle(color: Colors.red),
);
} else {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
return Container(
padding: EdgeInsets.symmetric(horizontal: 16),
child: GridView.count(
shrinkWrap: true,
crossAxisCount: 2,
physics: ClampingScrollPhysics(),
childAspectRatio: 0.6,
mainAxisSpacing: 6.0,
crossAxisSpacing: 6.0,
children: snapshot.data.map((wallpapers) {
return GridTile(
child: GestureDetector(
onTap: () {
// Navigator.push(context, MaterialPageRoute(builder: (context)=>ImageView(
// imageUrl: wallpapers.src.potrait,
// )));
},
child: Container(
child: ClipRRect(
borderRadius: BorderRadius.circular(10),
child: Image.network(
wallpapers.imageUrl,
fit: BoxFit.cover,
),
),
),
));
}).toList(),
),
);
},
);
}
}
}));
}
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: FrontPage(),
);
}
}
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;
void _incrementCounter() {
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
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.
);
}
}
There is a good implementation of a FutureBuilder widget
Future<List<dynamic>> getTrendingWallpapers() async {
String url = 'http://wallpaper.pkappstudio.info/api/api.php?action=get_recent';
final response = await http.get(url, headers: {"Accept": "application/json"});
if (response.statusCode == 200) {
List<dynamic> wallpapers = List();
wallpapers.add(response.body);
return wallpapers;
} else {
throw Exception('Failed to load post');
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder(
future: getTrendingWallpapers(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting || snapshot.connectionState == ConnectionState.none) {
return Center(child: CircularProgressIndicator());
}
if (snapshot.hasError) {
return Center(
child: Text('Future error'),
);
}
if (snapshot.hasData) {
return Center(
child: Text('Do something with your snapshot.data : \n ${snapshot.data}'),
);
}
},
),
);
}