How to pass Json data from one dart file to another? - json
I am trying to pass JSON data from Scryfall from my results.dart to display on my wishlist.dart after clicking the shopping bag button. I have no clue how to go about it. I mainly just want to display the name of the card, and the price. If i could get some help in the next hour, that'd be great! Here is the code:
RESULTS.DART:
import 'dart:async';
import 'package:demo_1/model/constant.dart';
import 'package:demo_1/viewscreen/wishlist_screen.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:demo_1/model/scryfall_1.dart';
import 'package:demo_1/model/tokens.dart';
import 'package:flutter/material.dart';
class GetProjectScreen extends StatefulWidget {
static const routeName = '/GetProjectScreen';
const GetProjectScreen({required this.user, Key? key}) : super(key: key);
final User user;
#override
State<StatefulWidget> createState() {
return _GetProjectState();
}
}
class _GetProjectState extends State<GetProjectScreen> {
late _Controller con;
#override
void initState() {
super.initState();
con = _Controller(this);
}
void render(fn) => setState(fn);
bool checked1 = true;
#override
Widget build(BuildContext context) {
final searchCard = ModalRoute.of(context)!.settings.arguments as Future<Scryfall>;
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
leading: BackButton(
color: Colors.white,
onPressed: () {
curToken = '';
Navigator.of(context).pop();
},
),
title: const Text('Showing Results For...'),
),
// body: Center(child: buildFutureBuilder(searchCard)),
body: Center(
child: FutureBuilder<Scryfall>(
future: searchCard,
builder: (context, snapshot) {
if (snapshot.hasData) {
List<String> prices = [
'\$' + snapshot.data!.prices.usd.toString(),
];
prices.removeWhere((item) => item.contains('null'));
for (int index = 0; index < prices.length; index++) {
if (prices[index].contains('\$') && !checked1) {
prices.removeAt(index);
}
}
return ListView(
padding: const EdgeInsets.all(8),
children: <Widget>[
Container(
width: 1000,
height: 500,
color: Colors.white,
child: Center(
child: Image(
image: NetworkImage(snapshot.data!.imageUris.borderCrop!),
),
),
),
ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: prices.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
tileColor: Colors.white,
title: Text(prices[index]),
onTap: () {
launchURL(
(prices[index].contains('\$')
? snapshot.data!.purchaseUris.tcgplayer
: (prices[index].contains('\€')
? snapshot.data!.purchaseUris.cardmarket
: snapshot.data!.purchaseUris.cardhoarder)),
);
},
trailing: Wrap(spacing: 10, children: <Widget>[
new IconButton(
icon: Icon(Icons.shopping_bag_sharp),
onPressed: () {
con.goToWishlist();
},
),
]),
);
},
),
],
);
//return cardFutureBuilder();
} else if (snapshot.hasError) {
return const Text('Either card does not exist or search is too vague');
}
return const CircularProgressIndicator();
},
),
),
endDrawer: Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: <Widget>[
const DrawerHeader(
decoration: BoxDecoration(
color: Colors.blue,
),
child: Text('Drawer Header'),
),
CheckboxListTile(
title: const Text("USD"),
value: checked1,
onChanged: (bool? value) {
setState(
() {
checked1 = value!;
},
);
},
),
),
],
),
),
),
);
}
void launchURL(String url) async {
if (!await launch(url)) throw 'Could not launch $url';
}
}
class _Controller {
_GetProjectState state;
_Controller(this.state) {
user = state.widget.user;
}
late User _user;
User get user => _user;
set user(User user) {
_user = user;
}
void goToWishlist() async {
await Navigator.pushNamed(
state.context,
WishlistScreen.routeName,
arguments: {
ArgKey.user: user,
},
);
state.render(() {});
}
}
WISHLIST.DART
import 'package:demo_1/model/constant.dart';
import 'package:demo_1/model/scryfall_1.dart';
import 'package:demo_1/viewscreen/confirmation_screen.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'results.dart';
import 'home_screen.dart';
class WishlistScreen extends StatefulWidget {
static const routeName = '/WishlistScreen';
const WishlistScreen({required this.user, Key? key}) : super(key: key);
final User user;
#override
State<StatefulWidget> createState() {
return _WishlistState();
}
}
class _WishlistState extends State<WishlistScreen> {
late _Controller con;
late String profilePicture;
Future<Scryfall>? searchCard;
final TextEditingController _controller = TextEditingController();
#override
void initState() {
super.initState();
con = _Controller(this);
profilePicture = widget.user.photoURL ?? 'No profile picture';
}
void render(fn) => setState(fn);
#override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: FloatingActionButton(
backgroundColor: Colors.cyan[400],
onPressed: () => con.searchDialog(),
child: const Icon(Icons.search),
),
appBar: AppBar(
title: const Text('Wish List'),
centerTitle: true,
),
body: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
const SizedBox(height: 18.0),
const CartItem(),
const CartItem(),
const CartItem(),
const SizedBox(height: 21.0),
MaterialButton(
onPressed: () {
setState(
() {
/*Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const ConfirmationScreen(),
));*/
con.confirmationScreen();
},
);
},
color: Colors.cyan,
height: 30.0,
minWidth: double.infinity,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
child: const Text(
"CHECKOUT",
style: TextStyle(
color: Colors.white,
fontSize: 14.0,
fontWeight: FontWeight.bold,
),
),
),
const SizedBox(height: 18.0),
],
)));
}
}
class CartItem extends StatelessWidget {
const CartItem({
Key? key,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Container(
color: const Color.fromARGB(255, 209, 206, 206),
margin: const EdgeInsets.symmetric(vertical: 8.0),
child: Row(
children: <Widget>[
Container(
width: 80.0,
height: 80.0,
child: Center(
child: Container(
width: 60.0,
height: 60.0,
decoration: BoxDecoration(
image: const DecorationImage(
fit: BoxFit.scaleDown,
image: NetworkImage(
"https://c1.scryfall.com/file/scryfall-cards/large/front/b/e/be524227-8adc-4b01-808f-5ec4ab9dc09c.jpg?1568004322",
),
),
borderRadius: BorderRadius.circular(15.0),
)))),
const SizedBox(width: 12.0),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
width: 100.0,
child: const Text(
"Default Card Name",
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
),
),
),
const SizedBox(height: 8.0),
Row(
children: <Widget>[
Container(
width: 20.0,
height: 20.0,
decoration: BoxDecoration(
color: const Color.fromARGB(255, 146, 143, 143),
borderRadius: BorderRadius.circular(4.0),
),
child: const Icon(
Icons.add,
color: Colors.white,
size: 15.0,
),
),
const Padding(
padding: EdgeInsets.symmetric(horizontal: 8.0),
child: Text(
"1",
style: TextStyle(
color: Colors.black,
fontSize: 16.0,
fontWeight: FontWeight.bold,
),
),
),
Container(
width: 20.0,
height: 20.0,
decoration: BoxDecoration(
color: const Color.fromARGB(255, 37, 114, 177),
borderRadius: BorderRadius.circular(4.0),
),
child: const Icon(
Icons.add,
color: Colors.white,
size: 15.0,
),
),
const Spacer(),
const Text(
"000.00",
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
),
),
],
),
],
),
),
],
),
);
}
}
class _Controller {
_WishlistState state;
_Controller(this.state) {
user = state.widget.user;
}
late User _user;
User get user => _user;
set user(User user) {
_user = user;
}
void confirmationScreen() async {
await Navigator.pushNamed(
state.context,
ConfirmationScreen.routeName,
arguments: {
ArgKey.user: user,
},
);
state.render(() {});
}
Future? searchDialog() {
return showDialog(
context: state.context,
builder: (BuildContext context) => AlertDialog(
title: const Text('Search'),
content: Container(
height: 180,
decoration: const BoxDecoration(
borderRadius: BorderRadius.all(
Radius.circular(10),
),
),
padding: const EdgeInsets.all(10),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text('Search for a card:'),
TextField(
controller: state._controller,
decoration: const InputDecoration(hintText: 'Enter Title'),
),
OutlinedButton(
onPressed: () {
state.setState(
() {
state.searchCard =
scryfallGet(state._controller.text.replaceAll(' ', '+'));
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
GetProjectScreen(user: state.widget.user),
settings: RouteSettings(arguments: state.searchCard)));
},
);
},
child: const Text('Search'),
),
],
),
),
),
);
}
}
SCRYFALL_1.DART
/*
* parsed with Nicol Bolas
*/
class Scryfall {
Scryfall({
required this.object,
required this.id,
required this.oracleId,
required this.multiverseIds,
required this.mtgoId,
required this.mtgoFoilId,
required this.tcgplayerId,
required this.cardmarketId,
required this.arenaId,
required this.name,
required this.lang,
required this.releasedAt,
required this.uri,
required this.scryfallUri,
required this.layout,
required this.highresImage,
required this.imageStatus,
required this.imageUris,
required this.manaCost,
required this.cmc,
required this.typeLine,
required this.oracleText,
required this.power,
required this.toughness,
required this.colors,
required this.colorIdentity,
required this.keywords,
required this.producedMana,
required this.legalities,
required this.games,
required this.reserved,
required this.foil,
required this.nonfoil,
required this.finishes,
required this.oversized,
required this.promo,
required this.reprint,
required this.variation,
required this.setId,
required this.scryfallSet,
required this.setName,
required this.setType,
required this.setUri,
required this.setSearchUri,
required this.scryfallSetUri,
required this.rulingsUri,
required this.printsSearchUri,
required this.collectorNumber,
required this.digital,
required this.rarity,
required this.watermark,
required this.flavorText,
required this.cardBackId,
required this.artist,
required this.artistIds,
required this.illustrationId,
required this.borderColor,
required this.frame,
required this.securityStamp,
required this.fullArt,
required this.textless,
required this.booster,
required this.storySpotlight,
required this.edhrecRank,
required this.prices,
required this.relatedUris,
required this.purchaseUris,
});
String object;
String id;
String? oracleId;
List<num> multiverseIds;
num? mtgoId;
num? mtgoFoilId;
num? tcgplayerId;
num? cardmarketId;
num? arenaId;
String name;
String lang;
DateTime releasedAt;
String uri;
String scryfallUri;
String? layout;
bool highresImage;
String imageStatus;
ImageUris imageUris;
String? manaCost;
num? cmc;
String? typeLine;
String? oracleText;
String? power;
String? toughness;
List<String> colors;
List<String> colorIdentity;
List<String> keywords;
List<String> producedMana;
Legalities legalities;
List<String> games;
bool reserved;
bool foil;
bool nonfoil;
List<String> finishes;
bool oversized;
bool promo;
bool reprint;
bool variation;
String setId;
String? scryfallSet;
String setName;
String setType;
String setUri;
String setSearchUri;
String scryfallSetUri;
String rulingsUri;
String printsSearchUri;
String collectorNumber;
bool digital;
String rarity;
String? watermark;
String? flavorText;
String cardBackId;
String artist;
List<String> artistIds;
String? illustrationId;
String borderColor;
String frame;
String? securityStamp;
bool fullArt;
bool textless;
bool booster;
bool storySpotlight;
num? edhrecRank;
Prices prices;
RelatedUris relatedUris;
PurchaseUris purchaseUris;
factory Scryfall.fromJson(Map<String, dynamic> json) => Scryfall(
object: json["object"],
id: json["id"],
oracleId: json["oracle_id"],
multiverseIds: json["multiverse_ids"] != null
? List<int>.from(json["multiverse_ids"].map((x) => x))
: [],
arenaId: json["arena_id"],
mtgoId: json["mtgo_id"],
mtgoFoilId: json["mtgo_foil_id"],
tcgplayerId: json["tcgplayer_id"],
cardmarketId: json["cardmarket_id"],
name: json["name"],
lang: json["lang"],
releasedAt: DateTime.parse(json["released_at"]),
uri: json["uri"],
scryfallUri: json["scryfall_uri"],
layout: json["layout"],
highresImage: json["highres_image"],
imageStatus: json["image_status"],
imageUris: ImageUris.fromJson(json["image_uris"]),
manaCost: json["mana_cost"],
cmc: json["cmc"],
typeLine: json["type_line"],
oracleText: json["oracle_text"],
power: json["power"],
toughness: json["toughness"],
colors: json["colors"] != null
? List<String>.from(json["colors"].map((x) => x))
: [],
colorIdentity: List<String>.from(json["color_identity"].map((x) => x)),
keywords: List<String>.from(json["keywords"].map((x) => x)),
producedMana: json["produced_mana"] != null
? List<String>.from(json["produced_mana"].map((x) => x))
: [],
legalities: Legalities.fromJson(json["legalities"]),
games: List<String>.from(json["games"].map((x) => x)),
reserved: json["reserved"],
foil: json["foil"],
nonfoil: json["nonfoil"],
finishes: List<String>.from(json["finishes"].map((x) => x)),
oversized: json["oversized"],
promo: json["promo"],
reprint: json["reprint"],
variation: json["variation"],
setId: json["set_id"],
scryfallSet: json["set"],
setName: json["set_name"],
setType: json["set_type"],
setUri: json["set_uri"],
setSearchUri: json["set_search_uri"],
scryfallSetUri: json["scryfall_set_uri"],
rulingsUri: json["rulings_uri"],
printsSearchUri: json["prints_search_uri"],
collectorNumber: json["collector_number"],
digital: json["digital"],
rarity: json["rarity"],
watermark: json["watermark"],
flavorText: json["flavor_text"],
cardBackId: json["card_back_id"],
artist: json["artist"],
artistIds: List<String>.from(json["artist_ids"].map((x) => x)),
illustrationId: json["illustration_id"],
borderColor: json["border_color"],
frame: json["frame"],
securityStamp: json["security_stamp"],
fullArt: json["full_art"],
textless: json["textless"],
booster: json["booster"],
storySpotlight: json["story_spotlight"],
edhrecRank: json["edhrec_rank"],
prices: Prices.fromJson(json["prices"]),
relatedUris: json["related_uris"] != null
? RelatedUris.fromJson(json["related_uris"])
: RelatedUris(
gatherer: "",
tcgplayerInfiniteArticles: "",
tcgplayerInfiniteDecks: "",
edhrec: "",
mtgtop8: ""),
purchaseUris: json["purchase_uris"] != null
? PurchaseUris.fromJson(json["purchase_uris"])
: PurchaseUris(tcgplayer: "", cardmarket: "", cardhoarder: ""),
);
Map<String, dynamic> toJson() => {
"object": object,
"id": id,
"oracle_id": oracleId,
"multiverse_ids": List<dynamic>.from(multiverseIds.map((x) => x)),
"mtgo_id": mtgoId,
"mtgo_foil_id": mtgoFoilId,
"tcgplayer_id": tcgplayerId,
"cardmarket_id": cardmarketId,
"name": name,
"lang": lang,
"released_at":
"${releasedAt.year.toString().padLeft(4, '0')}-${releasedAt.month.toString().padLeft(2, '0')}-${releasedAt.day.toString().padLeft(2, '0')}",
"uri": uri,
"scryfall_uri": scryfallUri,
"layout": layout,
"highres_image": highresImage,
"image_status": imageStatus,
"image_uris": imageUris.toJson(),
"mana_cost": manaCost,
"cmc": cmc,
"type_line": typeLine,
"oracle_text": oracleText,
"power": power,
"toughness": toughness,
"colors": List<dynamic>.from(colors.map((x) => x)),
"color_identity": List<dynamic>.from(colorIdentity.map((x) => x)),
"keywords": List<dynamic>.from(keywords.map((x) => x)),
"legalities": legalities.toJson(),
"games": List<dynamic>.from(games.map((x) => x)),
"reserved": reserved,
"foil": foil,
"nonfoil": nonfoil,
"finishes": List<dynamic>.from(finishes.map((x) => x)),
"oversized": oversized,
"promo": promo,
"reprint": reprint,
"variation": variation,
"set_id": setId,
"set": scryfallSet,
"set_name": setName,
"set_type": setType,
"set_uri": setUri,
"set_search_uri": setSearchUri,
"scryfall_set_uri": scryfallSetUri,
"rulings_uri": rulingsUri,
"prints_search_uri": printsSearchUri,
"collector_number": collectorNumber,
"digital": digital,
"rarity": rarity,
"watermark": watermark,
"flavor_text": flavorText,
"card_back_id": cardBackId,
"artist": artist,
"artist_ids": List<dynamic>.from(artistIds.map((x) => x)),
"illustration_id": illustrationId,
"border_color": borderColor,
"frame": frame,
"security_stamp": securityStamp,
"full_art": fullArt,
"textless": textless,
"booster": booster,
"story_spotlight": storySpotlight,
"edhrec_rank": edhrecRank,
"prices": prices.toJson(),
"related_uris": relatedUris.toJson(),
"purchase_uris": purchaseUris.toJson(),
};
}
class ImageUris {
ImageUris({
required this.small,
required this.normal,
required this.large,
required this.png,
required this.artCrop,
required this.borderCrop,
});
String? small;
String? normal;
String? large;
String? png;
String? artCrop;
String? borderCrop;
factory ImageUris.fromJson(Map<String, dynamic> json) => ImageUris(
small: json["small"],
normal: json["normal"],
large: json["large"],
png: json["png"],
artCrop: json["art_crop"],
borderCrop: json["border_crop"],
);
Map<String, dynamic> toJson() => {
"small": small,
"normal": normal,
"large": large,
"png": png,
"art_crop": artCrop,
"border_crop": borderCrop,
};
}
class Legalities {
Legalities({
required this.standard,
required this.future,
required this.historic,
required this.gladiator,
required this.pioneer,
required this.modern,
required this.legacy,
required this.pauper,
required this.vintage,
required this.penny,
required this.commander,
required this.brawl,
required this.historicbrawl,
required this.alchemy,
required this.paupercommander,
required this.duel,
required this.oldschool,
required this.premodern,
});
String? standard;
String? future;
String? historic;
String? gladiator;
String? pioneer;
String? modern;
String? legacy;
String? pauper;
String? vintage;
String? penny;
String? commander;
String? brawl;
String? historicbrawl;
String? alchemy;
String? paupercommander;
String? duel;
String? oldschool;
String? premodern;
factory Legalities.fromJson(Map<String, dynamic> json) => Legalities(
standard: json["standard"],
future: json["future"],
historic: json["historic"],
gladiator: json["gladiator"],
pioneer: json["pioneer"],
modern: json["modern"],
legacy: json["legacy"],
pauper: json["pauper"],
vintage: json["vintage"],
penny: json["penny"],
commander: json["commander"],
brawl: json["brawl"],
historicbrawl: json["historicbrawl"],
alchemy: json["alchemy"],
paupercommander: json["paupercommander"],
duel: json["duel"],
oldschool: json["oldschool"],
premodern: json["premodern"],
);
Map<String, dynamic> toJson() => {
"standard": standard,
"future": future,
"historic": historic,
"gladiator": gladiator,
"pioneer": pioneer,
"modern": modern,
"legacy": legacy,
"pauper": pauper,
"vintage": vintage,
"penny": penny,
"commander": commander,
"brawl": brawl,
"historicbrawl": historicbrawl,
"alchemy": alchemy,
"paupercommander": paupercommander,
"duel": duel,
"oldschool": oldschool,
"premodern": premodern,
};
}
class Prices {
Prices({
required this.usd,
required this.usdFoil,
required this.usdEtched,
required this.eur,
required this.eurFoil,
required this.tix,
});
String? usd;
String? usdFoil;
dynamic usdEtched;
String? eur;
String? eurFoil;
String? tix;
factory Prices.fromJson(Map<String, dynamic> json) => Prices(
usd: json["usd"],
usdFoil: json["usd_foil"],
usdEtched: json["usd_etched"],
eur: json["eur"],
eurFoil: json["eur_foil"],
tix: json["tix"],
);
Map<String, dynamic> toJson() => {
"usd": usd,
"usd_foil": usdFoil,
"usd_etched": usdEtched,
"eur": eur,
"eur_foil": eurFoil,
"tix": tix,
};
}
class PurchaseUris {
PurchaseUris({
required this.tcgplayer,
required this.cardmarket,
required this.cardhoarder,
});
String tcgplayer;
String cardmarket;
String cardhoarder;
factory PurchaseUris.fromJson(Map<String, dynamic> json) => PurchaseUris(
tcgplayer: json["tcgplayer"],
cardmarket: json["cardmarket"],
cardhoarder: json["cardhoarder"],
);
Map<String, dynamic> toJson() => {
"tcgplayer": tcgplayer,
"cardmarket": cardmarket,
"cardhoarder": cardhoarder,
};
}
class RelatedUris {
RelatedUris({
required this.gatherer,
required this.tcgplayerInfiniteArticles,
required this.tcgplayerInfiniteDecks,
required this.edhrec,
required this.mtgtop8,
});
String gatherer;
String tcgplayerInfiniteArticles;
String tcgplayerInfiniteDecks;
String edhrec;
String mtgtop8;
factory RelatedUris.fromJson(Map<String, dynamic> json) => RelatedUris(
gatherer: json["gatherer"],
tcgplayerInfiniteArticles: json["tcgplayer_infinite_articles"],
tcgplayerInfiniteDecks: json["tcgplayer_infinite_decks"],
edhrec: json["edhrec"],
mtgtop8: json["mtgtop8"],
);
Map<String, dynamic> toJson() => {
"gatherer": gatherer,
"tcgplayer_infinite_articles": tcgplayerInfiniteArticles,
"tcgplayer_infinite_decks": tcgplayerInfiniteDecks,
"edhrec": edhrec,
"mtgtop8": mtgtop8,
};
}
Related
How to send json data from on route to another route
In my Flutter application, I am trying to pass JSON data from one route to another. The challenge I am facing is how to pass a list as a parameter. The first screen contains a list of JSON data that has been fetched, and I aim to show the complete details of each item when the user clicks on the respective ListTile. you will find the onTap() in JsonParsingPodo.dart here's my code : posts.dart (plain old dart object file) class PostList { final List<Post> posts; PostList({required this.posts}); factory PostList.fromJson(Map<String, dynamic> parsedJson) { List<dynamic> postsJson = parsedJson['posts'] as List; List<Post> posts = <Post>[]; posts = postsJson.map((e) => Post.fromJson(e)).toList(); return PostList(posts: posts); } } class Post { int userId; int id; String title; String body; Post( {required this.id, required this.body, required this.title, required this.userId}); factory Post.fromJson(Map<String, dynamic> json) { return Post( id: json['id'], body: json['body'], title: json['title'], userId: json['userId']); } } JsonParsingPodo.dart (First Screen) import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:http/http.dart'; import 'package:podo_practice/posts.dart'; import 'display.dart'; class JsonParsingPodo extends StatefulWidget { const JsonParsingPodo({super.key}); #override State<JsonParsingPodo> createState() => _JsonParsingPodoState(); } class _JsonParsingPodoState extends State<JsonParsingPodo> { late Future<PostList> data; #override void initState() { super.initState(); Network network = Network("https://dummyjson.com/posts"); data = network.loadPost(); } #override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( centerTitle: true, title: const Text("PODO: json"), ), body: Center( // ignore: avoid_unnecessary_containers child: Container( child: FutureBuilder( future: data, builder: (context, AsyncSnapshot<PostList> snapshot) { List<Post> allposts; if (snapshot.hasData) { allposts = snapshot.data!.posts; return createListView(allposts, context); } return const CircularProgressIndicator(); }), ), )); } Widget createListView(List<Post> data, BuildContext context) { return ListView.builder( itemCount: data.length, itemBuilder: (context, int index) { return Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ const Divider( height: 5.0, ), ListTile( title: Text("${data[index].title}"), subtitle: Text("${data[index].body}"), leading: Column( children: <Widget>[ CircleAvatar( backgroundColor: Colors.green, radius: 23, child: Text("${data[index].id}"), ), ], ), onTap: () { Navigator.push( context, MaterialPageRoute( builder: (context) => const DisplayData()), // *what to pass here??* ); }, ), ], ); }); } } class Network { final String url; Network(this.url); Future<PostList> loadPost() async { final response = await get(Uri.parse(Uri.encodeFull(url))); if (response.statusCode == 200) { //ok return PostList.fromJson(json.decode(response.body)); } else { throw Exception("Failed to load data. "); } } } DisplayData.dart (Second Screen) import 'package:flutter/material.dart'; import 'package:podo_practice/posts.dart'; class DisplayData extends StatefulWidget { const DisplayData({super.key}); #override State<DisplayData> createState() => _DisplayDataState(); } class _DisplayDataState extends State<DisplayData> { late Future<PostList> data; #override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( centerTitle: true, title: const Text("Display Post"), ), body: Padding( padding: const EdgeInsets.all(8.0), child: Card( child: Column( children: [ // Text(data); ], ), ), ), ); } } I have recently started learning Flutter and don't have much knowledge. I tried reading articles on Stack Overflow about this thing, but I didn't understand much. So, I have decided to post a question for help. Please assist me in completing the following code. On the "Display Data" page, I need to display the **title **and its **description **when the user clicks on the ListItem.
onListile tap send particular object using index Widget createListView(List<Post> data, BuildContext context) { return ListView.builder( itemCount: data.length, itemBuilder: (context, int index) { Post post = data[index] return Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ const Divider( height: 5.0, ), ListTile( title: Text("${data[index].title}"), subtitle: Text("${data[index].body}"), leading: Column( children: <Widget>[ CircleAvatar( backgroundColor: Colors.green, radius: 23, child: Text("${data[index].id}"), ), ], ), onTap: () { Navigator.push( context, MaterialPageRoute( builder: (context) => const DisplayData(post:post)), // *what to pass here??* ); }, ), ], ); }); } } get post on constructor to display import 'package:flutter/material.dart'; import 'package:podo_practice/posts.dart'; class DisplayData extends StatefulWidget { final Post post; const DisplayData({super.key,required this.post}); #override State<DisplayData> createState() => _DisplayDataState(); } class _DisplayDataState extends State<DisplayData> { late Future<PostList> data; #override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( centerTitle: true, title: const Text("Display Post"), ), body: Padding( padding: const EdgeInsets.all(8.0), child: Card( child: Column( children: [ // Text(data); ], ), ), ), ); } }
How can i access an object in a list with it's property as search query?
I have a UserModel class which converts a JSON body. I now want to search a List of these UserModels with an emailadres which I got from a different dart page/file. I have an ApiService class which retrieves all users, it then calls the UserModel class to parse and put them in a List. I now want to be able to search the list of UserModel with emailadres to display the data of this user. ApiService class class ApiService { Future<List<UserModel>?> getUnacceptedProfiles() async { try { var url = Uri.parse(apis.baseUrl + apis.unAcceptedProfiles); var response = await http.get(url); if (response.statusCode == 200) { List<UserModel> model = List<UserModel>.from( json.decode(response.body)['data'].map( (x) => UserModel.fromJson(x))); return _model; } } catch (e) { print(e.toString()); } } } UserModel class // To parse required this JSON data, do // // final UserModel = userModelFromJson(jsonString); import 'dart:convert'; UserModel userModelFromJson(String str) => UserModel.fromJson(json.decode(str)); String userModelToJson(UserModel data) => json.encode(data.toJson()); class UserModel { UserModel({ required this.status, required this.result, }); int status; List<Result> result; factory UserModel.fromJson(Map<String, dynamic> json) => UserModel( status: json["status"], result: List<Result>.from(json["result"].map((x) => Result.fromJson(x))), ); Map<String, dynamic> toJson() => { "status": status, "result": List<dynamic>.from(result.map((x) => x.toJson())), }; } class Result { Result({ required this.docentId, required this.naam, required this.achternaam, required this.emailadres, required this.geboortedatum, required this.geboorteplaats, this.maxRijafstand, this.heeftRijbewijs, this.heeftAuto, required this.straat, required this.huisnummer, required this.geslacht, required this.nationaliteit, required this.woonplaats, required this.postcode, required this.land, required this.wachtwoord, required this.isAccepted, this.isFlexwerker, }); int docentId; String naam; String achternaam; String emailadres; DateTime geboortedatum; String geboorteplaats; dynamic maxRijafstand; dynamic heeftRijbewijs; dynamic heeftAuto; String straat; int huisnummer; String geslacht; String nationaliteit; String woonplaats; String postcode; String land; String wachtwoord; int isAccepted; dynamic isFlexwerker; factory Result.fromJson(Map<String, dynamic> json) => Result( docentId: json["docentID"], naam: json["naam"], achternaam: json["achternaam"], emailadres: json["emailadres"], geboortedatum: DateTime.parse(json["geboortedatum"]), geboorteplaats: json["geboorteplaats"], maxRijafstand: json["maxRijafstand"], heeftRijbewijs: json["heeftRijbewijs"], heeftAuto: json["heeftAuto"], straat: json["straat"], huisnummer: json["huisnummer"], geslacht: json["geslacht"], nationaliteit: json["nationaliteit"], woonplaats: json["woonplaats"], postcode: json["postcode"], land: json["land"], wachtwoord: json["wachtwoord"], isAccepted: json["isAccepted"], isFlexwerker: json["isFlexwerker"], ); Map<String, dynamic> toJson() => { "docentID": docentId, "naam": naam, "achternaam": achternaam, "emailadres": emailadres, "geboortedatum": geboortedatum.toIso8601String(), "geboorteplaats": geboorteplaats, "maxRijafstand": maxRijafstand, "heeftRijbewijs": heeftRijbewijs, "heeftAuto": heeftAuto, "straat": straat, "huisnummer": huisnummer, "geslacht": geslacht, "nationaliteit": nationaliteit, "woonplaats": woonplaats, "postcode": postcode, "land": land, "wachtwoord": wachtwoord, "isAccepted": isAccepted, "isFlexwerker": isFlexwerker, }; } Data fetch part in userView _singleProfilePageState({required this.emailadres}); late List<UserModel>? _userModel = []; #override void initState() { super.initState(); _getData(); } void _getData() async { _userModel = (await ApiService().getUnacceptedProfiles())!; Map<UserModel, dynamic> user = jsonDecode(_userModel); } profileview page import 'dart:convert'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:skoolworkshop/colors.dart'; import 'package:skoolworkshop/main.dart'; import 'package:skoolworkshop/profiles.dart'; import '/Model/userModel.dart'; import 'package:skoolworkshop/apis.dart'; import 'package:intl/intl.dart'; import 'package:http/http.dart' as http; import 'api_service.dart'; import 'package:get/get.dart'; import 'Widgets/profile_widget.dart'; class singleProfilePage extends StatefulWidget { singleProfilePage({Key? key, required this.emailadres}) : super(key: key); String emailadres; #override State<singleProfilePage> createState() => _singleProfilePageState(emailadres: this.emailadres); } class _singleProfilePageState extends State<singleProfilePage> { final String getAcceptedUser = apis.baseUrl + apis.acceptedProfiles; DateFormat dateFormat = DateFormat("yyyy-dd-MM HH:mm:ss"); DateFormat properDate = DateFormat("yyyy-dd-MM"); String emailadres; _singleProfilePageState({required this.emailadres}); List<UserModel>? userModel = []; #override void initState() { super.initState(); getData(); } void getData() async { userModel = (await ApiService().getUnacceptedProfiles())!; final filteredUsers = userModel?.where((um) => um.result.indexWhere((r) => r.emailadres == emailadres,) >= 0,); } #override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text( 'Profiel', style: Theme.of(context).textTheme.headline1, )), body: ListView( physics: BouncingScrollPhysics(), padding: EdgeInsets.all(20), children: [ ProfilePictureWidget( imagePath: // "https://cdn.dribbble.com/users/113499/screenshots/12787572/media/3a8bf7d51271e03e8beaef830c5babf2.png?compress=1&resize=1600x1200&vertical=top" "https://www.personality-insights.com/wp-content/uploads/2017/12/default-profile-pic-e1513291410505.jpg", onClicked: () async {}, ), const SizedBox(height: 12), //Naam en email worden meegegeven in buildName methode :) buildName(), const SizedBox(height: 6), const Divider( height: 20, thickness: 1, color: Colors.black, ), const SizedBox(height: 4), buildInfo(), const SizedBox(height: 4), const Divider( height: 20, thickness: 1, color: Colors.black, ), ], ), ); } Widget buildName(/*results*/) => Column( children: [ Text(filteredUsers[0].Results[0].naam + "Achternaam", style: Theme.of(context).textTheme.headline2, ), Text("Emailadres", style: Theme.of(context).textTheme.bodyText1) ], ); Widget buildInfo(/*results*/) => Container( padding: EdgeInsets.all(5), child: Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ Text("Docent informatie", style: Theme.of(context).textTheme.headline3), const SizedBox( height: 5, ), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, crossAxisAlignment: CrossAxisAlignment.start, children: [ Expanded( child: Text( "Geslacht: " "Vrouw " "Geboortedatum: " "01-01-2000", style: Theme.of(context).textTheme.bodyText1)), Expanded( child: Text("Rijbewijs: " "Ja " "Auto: " "Nee", style: Theme.of(context).textTheme.bodyText1)) ], ), const SizedBox( height: 5, ), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, crossAxisAlignment: CrossAxisAlignment.start, children: [ Expanded( child: Text("Telefoonnummer: " "06-12345678", style: Theme.of(context).textTheme.bodyText1)), Expanded( child: Text( "Adres: " "straat: " "nr: " "postcode: " "woonplaats: ", style: Theme.of(context).textTheme.bodyText1)) ], ), const SizedBox( height: 10, ) ], ), ); }
You can use where to filter the user list based on your criteria and indexWhere to search the inner results.: final filteredUsers = model.where( (um) => um.results.indexWhere( (r) => r.emailadres == 'your email address', ) >= 0, );
type 'List<dynamic>' is not a subtype of type 'List<MaintenanceInfo>' of 'function result'
I want to change List data; (List < dynamic> data) to List<MaintenanceInfo> data; class MaintenanceInfo { final String serial; MaintenanceInfo({this.serial,}); factory MaintenanceInfo.fromJson(Map<String, dynamic> json) { return new MaintenanceInfo( serial: json['serial'], );}} Or is there any way to extract JSON data as forEach? I am trying to follow this example (https://stackoverflow.com/a/50569613/12908336) and am facing such a problem.
Check out this example that i have created for you : import 'dart:async'; import 'package:flutter/material.dart'; import 'dart:convert'; //import 'package:http/http.dart' as http; void main() => runApp(new MaterialApp( home: new HomePage(), debugShowCheckedModeBanner: false, )); class HomePage extends StatefulWidget { #override _HomePageState createState() => new _HomePageState(); } class _HomePageState extends State<HomePage> { TextEditingController controller = new TextEditingController(); String apiData = '''{"ResultText": "Success","ResultStatus": 0,"data": [{"serial": "sample1"},{"serial": "sample2"},{"serial": "sample3"},{"serial": "sample4"},{"serial": "sample5"},{"serial": "sample6"}]} '''; // Get json result and convert it to model. Then add Future<Null> getUserDetails() async { // final response = await http.get(url); // final responseJson = json.decode(response.body); // this is where you apis gets hit i have taken the sample json you provided. final maintenanceInfo = maintenanceInfoFromJson(apiData); setState(() { /* for (Map user in responseJson) { _userDetails.add(UserDetails.fromJson(user)); } */ maintenanceInfo.data.forEach((element) { _userDetails.add(element); }); }); } #override void initState() { super.initState(); getUserDetails(); } #override Widget build(BuildContext context) { return new Scaffold( appBar: new AppBar( title: new Text('Home'), elevation: 0.0, ), body: new Column( children: <Widget>[ new Container( color: Theme.of(context).primaryColor, child: new Padding( padding: const EdgeInsets.all(8.0), child: new Card( child: new ListTile( leading: new Icon(Icons.search), title: new TextField( controller: controller, decoration: new InputDecoration( hintText: 'Search', border: InputBorder.none), onChanged: onSearchTextChanged, ), trailing: new IconButton( icon: new Icon(Icons.cancel), onPressed: () { controller.clear(); onSearchTextChanged(''); }, ), ), ), ), ), new Expanded( child: _searchResult.length != 0 || controller.text.isNotEmpty ? new ListView.builder( itemCount: _searchResult.length, itemBuilder: (context, i) { return new Card( child: new ListTile( title: new Text(_searchResult[i].serial), ), margin: const EdgeInsets.all(0.0), ); }, ) : new ListView.builder( itemCount: _userDetails.length, itemBuilder: (context, index) { return new Card( child: new ListTile( title: new Text(_userDetails[index].serial), ), margin: const EdgeInsets.all(0.0), ); }, ), ), ], ), ); } onSearchTextChanged(String text) async { _searchResult.clear(); if (text.isEmpty) { setState(() {}); return; } _userDetails.forEach((userDetail) { if (userDetail.serial.contains(text)) _searchResult.add(userDetail); }); setState(() {}); } } List<Serials> _searchResult = []; List<Serials> _userDetails = []; // To parse this JSON data, do // // final maintenanceInfo = maintenanceInfoFromJson(jsonString); MaintenanceInfo maintenanceInfoFromJson(String str) => MaintenanceInfo.fromJson(json.decode(str)); String maintenanceInfoToJson(MaintenanceInfo data) => json.encode(data.toJson()); class MaintenanceInfo { MaintenanceInfo({ this.resultText, this.resultStatus, this.data, }); String resultText; int resultStatus; List<Serials> data; factory MaintenanceInfo.fromJson(Map<String, dynamic> json) => MaintenanceInfo( resultText: json["ResultText"], resultStatus: json["ResultStatus"], data: List<Serials>.from(json["data"].map((x) => Serials.fromJson(x))), ); Map<String, dynamic> toJson() => { "ResultText": resultText, "ResultStatus": resultStatus, "data": List<dynamic>.from(data.map((x) => x.toJson())), }; } class Serials { Serials({ this.serial, }); String serial; factory Serials.fromJson(Map<String, dynamic> json) => Serials( serial: json["serial"], ); Map<String, dynamic> toJson() => { "serial": serial, }; } Let me know if it works.
I have a response of json body from a login API . I made a model class for that json. Now how to use it in my pages to fetch data?
I have logged in from a api . Then i got a response of json . I can fetch data from login to homepage . For that i created a constructor in homepage and pass it in Login page where i made navigator for the homepage . But i know it's not good practice to fetch data like it. using model class is more smart way. I added my code here of login, homepage and model . Now my data can only communicate between these two page . But i need to fetch data to another pages too. login.dart import 'package:api_login/model/response_model.dart'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'dart:convert'; import '../sharePreference.dart'; import 'homepage.dart'; class Login extends StatefulWidget { UserDetails userDetails = new UserDetails(); #override _LoginState createState() => _LoginState(); } class _LoginState extends State<Login> { var notification ; bool isprocesscomplete = false; TextEditingController _userController = TextEditingController(); TextEditingController _passwordController = TextEditingController(); final _scaffoldKey = GlobalKey<ScaffoldState>(); String BaseUrl = "my url"; #override Widget build(BuildContext context) { return Scaffold( key: _scaffoldKey, body: SingleChildScrollView( child: Center( child: Container( height: 770, color: Colors. lightBlue, padding: EdgeInsets.fromLTRB(20, 100, 20, 20), child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Text( "Login", style: TextStyle(fontSize: 32), ), SizedBox( height: 30, ), Card( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(20), ), child: Container( height: 220, width: MediaQuery.of(context).size.width, decoration: BoxDecoration( borderRadius: BorderRadius.circular(20), ), child: Column( children: [ Padding( padding: const EdgeInsets.all(30), child: TextField( controller: _userController, decoration: InputDecoration(hintText: "Username"), ), ), Padding( padding: const EdgeInsets.all(30), child: TextField( controller: _passwordController, obscureText: true, decoration: InputDecoration(hintText: "Password"), ), ), ], ), ), ), SizedBox( height: 60, width: MediaQuery.of(context).size.width, child: RaisedButton( color: Colors.blue, onPressed: () { if (_userController.text == "" || _passwordController.text == "") { final snackBar = SnackBar( content: Text("Enter Username and Password")); _scaffoldKey.currentState.showSnackBar(snackBar); } else { signIn(_userController.text, _passwordController.text); } }, child: ProgressButton(), shape: RoundedRectangleBorder( borderRadius: new BorderRadius.circular(16), ), ), ), SizedBox( height: 20, ), FlatButton( child: Text("Forgot password"), onPressed: () {}, ), ], ), ), ), ), ); } Widget ProgressButton() { if (isprocesscomplete != false) { return CircularProgressIndicator( valueColor: AlwaysStoppedAnimation<Color>(Colors.white)); } else { return new Text( "Sign In", style: const TextStyle( color: Colors.white, fontSize: 15.0, ), ); } } void signIn(String username, String password) async { setState(() { isprocesscomplete = true; }); var response = await http.post(BaseUrl, headers: {"Content-Type": "application/json"}, body: json.encode({ "username": username, "password": password, })); Map<String, dynamic> value = json.decode(response.body); notification = value["notifications"]; // print('Response ${response.body}'); if (response.statusCode == 200) { try { ///You don't need it but it will be cool for show progress dialgo for 4 second then redirect even if we get reslut Future.delayed(Duration(seconds: 4), () { // 5s over make it false setState(() { isprocesscomplete = true; }); }); Map<String, dynamic> value = json.decode(response.body); print('Response ${response.body}'); SharedPrefrence().setToken(value['api_token'].toString()); SharedPrefrence().setName(value['user_name']); SharedPrefrence().setUserId(value['user_id'].toString()); ///This is used when user loged in you can set this true, ///next time you open you need to check loginc in main.dart or splashscreen if this is true if it is true then ///redirect to home page it is false then redirect to Login page ///When you logout the app make sure you set this as false like "SharedPrefrence().setLoggedIn(false);" SharedPrefrence().setLoggedIn(true); ///Redirect to Home page Navigator.pushAndRemoveUntil( context, MaterialPageRoute( builder: (context) => HomePage( user_name: value['user_name'], api_token: value['api_token'], notification: notification, // payment: payment , )), ModalRoute.withName("/login")); } catch (e) { e.toString(); final snackBar = SnackBar( content: Text("something wrong,Try again 😑"), behavior: SnackBarBehavior.floating, ); _scaffoldKey.currentState.showSnackBar(snackBar); } } else { var message = value['error']; final snackBar = SnackBar( backgroundColor: Colors.redAccent[700], content: Text(message.toString()), behavior: SnackBarBehavior.floating, ); _scaffoldKey.currentState.showSnackBar(snackBar); } } } homepage.dart import 'package:api_login/model/response_model.dart'; import 'package:api_login/pages/details.dart'; import 'package:api_login/pages/settingPage.dart'; import 'package:api_login/widget/neumorphsm.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:shared_preferences/shared_preferences.dart'; import '../sharePreference.dart'; import 'login.dart'; import 'login.dart'; class HomePage extends StatefulWidget { final payment; final count ; String user_name; final api_token; final user_id ; final payment_id; final List<dynamic> notification ; // List data ; HomePage({ this.user_name, this.api_token , this.user_id, #required this.notification , this.count, this.payment, this.payment_id}); #override _HomePageState createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { String arrayLength ; String nametoprint; String tokentoprint; #override void initState() { super.initState(); Future name = SharedPrefrence().getName(); name.then((data) async { nametoprint = data; print(nametoprint); }); Future token= SharedPrefrence().getToken(); token.then((data) async { tokentoprint= data; print(tokentoprint); }); } int counter ; #override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text("Cash-Management"), backgroundColor: Colors.blue, actions: [ new Stack( children: <Widget>[ new IconButton(icon: Icon(Icons.notifications), onPressed: () { setState(() { counter = 0; }); }), counter != 0 ? new Positioned( right: 11, top: 11, child: new Container( padding: EdgeInsets.all(2), decoration: new BoxDecoration( color: Colors.red, borderRadius: BorderRadius.circular(6), ), constraints: BoxConstraints( minWidth: 14, minHeight: 14, ), child: Text( " ${widget.notification.length} ", style: TextStyle( color: Colors.white, fontSize: 8, ), textAlign: TextAlign.center, ), ), ) : new Container() ], ), IconButton( icon: Icon(Icons.exit_to_app), onPressed: () { Navigator.push( context, MaterialPageRoute(builder: (context) => Login()), ); }), ], ), body: ListView( children: <Widget>[ Card( color: Colors.lightBlue, child: InkWell( onTap: () { Navigator.push( context, new MaterialPageRoute( builder: (BuildContext context) => new SettingPage())); }, child: Container( height: 120, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( "Profile", style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold), ), Text( "Name:${widget.user_name}", // " ${widget.username} ", style: TextStyle(fontSize: 16), ), // Text( // " ${widget.notification.length} ",), // Text(" ${nametoprint} "), ], ), ), ), ), Container( color: Colors.lightBlue, height: 400, child: ListView.builder( itemCount: widget.notification == null ? 0 : widget.notification.length, itemBuilder: (context, index){ final count = widget.notification ; print(count.length); return Card( color: Colors.blue, child: InkWell( onTap: () { Navigator.push( context, new MaterialPageRoute( builder: (BuildContext context) => new DetailPage())); }, child: Column( children:<Widget>[ Text('Amount'), ListTile( title: Text(widget.notification[index] ["data"]["amount"].toString()), subtitle: Text(widget.notification[index]["data"]["message"].toString()), ) , Text('Created at '), ListTile( title: Text(widget.notification[index] ["created_at"].toString()), ), Text('updated at'), ListTile( title: Text(widget.notification[index] ["updated_at"].toString()), ), ], ), ), ); }), ), Container( color: Colors.blue, height: 130, child: Button() ), ], ), // floatingActionButton: FloatingActionButton(onPressed: () { // print("Increment Counter"); // setState(() { // counter++; // }); // }, child: Icon(Icons.add),), ), ); } } response_model.dart class UserDetails { int userId; String userName; String apiToken; List<Notifications> notifications; UserDetails({this.userId, this.userName, this.apiToken, this.notifications}); UserDetails.fromJson(Map<String, dynamic> json) { userId = json['user_id']; userName = json['user_name']; apiToken = json['api_token']; if (json['notifications'] != null) { notifications = new List<Notifications>(); json['notifications'].forEach((v) { notifications.add(new Notifications.fromJson(v)); }); } } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['user_id'] = this.userId; data['user_name'] = this.userName; data['api_token'] = this.apiToken; if (this.notifications != null) { data['notifications'] = this.notifications.map((v) => v.toJson()).toList(); } return data; } } class Notifications { String id; String type; int notifiableId; String notifiableType; Data data; Null readAt; String createdAt; String updatedAt; Notifications( {this.id, this.type, this.notifiableId, this.notifiableType, this.data, this.readAt, this.createdAt, this.updatedAt}); Notifications.fromJson(Map<String, dynamic> json) { id = json['id']; type = json['type']; notifiableId = json['notifiable_id']; notifiableType = json['notifiable_type']; data = json['data'] != null ? new Data.fromJson(json['data']) : null; readAt = json['read_at']; createdAt = json['created_at']; updatedAt = json['updated_at']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['id'] = this.id; data['type'] = this.type; data['notifiable_id'] = this.notifiableId; data['notifiable_type'] = this.notifiableType; if (this.data != null) { data['data'] = this.data.toJson(); } data['read_at'] = this.readAt; data['created_at'] = this.createdAt; data['updated_at'] = this.updatedAt; return data; } } class Data { int paymentId; String generatePaymentId; String message; int amount; Data({this.paymentId, this.generatePaymentId, this.message, this.amount}); Data.fromJson(Map<String, dynamic> json) { paymentId = json['payment_id']; generatePaymentId = json['generate_payment_id']; message = json['message']; amount = json['amount']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['payment_id'] = this.paymentId; data['generate_payment_id'] = this.generatePaymentId; data['message'] = this.message; data['amount'] = this.amount; return data; } } It will be helpful if anyone let e know how to show detail page from this section. ListView.builder( itemCount: widget.notification == null ? 0 : widget.notification.length, itemBuilder: (context, index){ final count = widget.notification ; print(count.length); return Card( color: Colors.blue, child: InkWell( onTap: () { Navigator.push( context, new MaterialPageRoute( builder: (BuildContext context) => new DetailPage())); },
You can use widget.user_name, widget.api_token in HomePage, and pass it to Details Page. Home Page Navigator.push( context, new MaterialPageRoute( builder: (BuildContext context) => new DetailPage(userName :widget.user_name, apiToken: widget.api_token)));
If you want the data to be used globally in your application, perhaps you can fetch your data from API before MaterialApp() so that your data can be used globally. Other way is you can pass your UserDetails() data to next page by calling them inside your Navigator.push(). You can read more detail example here
How to return json data from local storage in flutter app
I have json file and i want to display it in Container. I have tried many things but nothing works. For now, I have this error I have tried with jsonDecode(), i know it returns a map like this Map<String, dynamic>, but i don't know how to fix this I have Product class and ItemCard class: class ItemCard extends StatelessWidget{ final Product product; final Function press; const ItemCard({ Key key, this.product, this.press }) : super(key: key); #override Widget build(BuildContext context){ return GestureDetector( onTap: press, child: Column( children: <Widget>[ Expanded( child: Container( padding: EdgeInsets.all(20), decoration: BoxDecoration( color: Colors.green, borderRadius: BorderRadius.circular(16), ), /* child: Hero( tag: "${product.id}", child: Image.asset(product.image), ), */ ), ), Text(product.brand), ], ), ); } } And in body, my List: Container( child: Expanded( child: FutureBuilder( future: DefaultAssetBundle.of(context) .loadString('assets/watches.json'), builder: (context,snapshot){ //print(snapshot.data); var jsondata = jsonDecode(snapshot.data.toString()); return GridView.builder( itemCount: jsondata.length, gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, mainAxisSpacing: 10, crossAxisSpacing: 10, childAspectRatio: 0.75 ), itemBuilder: (context, index) => ItemCard( product: jsondata[index], press: (){} ), ); }, ), ), ), How can I fix this? any idea would help
You need to convert jsondata[index] that is a map into a Product instance. Normally you would have a fromJson method to create the instance from a json map. product: Product.fromJson(jsondata[index]), This is an example of toJson and fromJson implementation class User { final String name; final String email; User(this.name, this.email); User.fromJson(Map<String, dynamic> json) : name = json['name'], email = json['email']; Map<String, dynamic> toJson() => { 'name': name, 'email': email, }; }