how to pass multiple data to another screen flutter - flutter

I already have a method to pass data. It can only pass one argument, but I want it to pass at least two arguments. How can I do that?
screen1
GestureDetector(
onTap: () => Navigator.of(context).push(PageTransition(settings: RouteSettings(
arguments:imageUrl,),type: PageTransitionType.fade,
child: const ShowPictureScreen())),
Receive on Screen2
#override
Widget build(BuildContext context) {
final data = ModalRoute.of(context)!.settings;
late String photoUrl;
if (data.arguments == null) {
photoUrl = "empty";
} else {
photoUrl = data.arguments as String;
}
...
Text('photoUrl')

you can pass multiple data using the following code
// screen1.dart
..
Expanded(
child: RaisedButton(
onPressed: () {
Navigator.push(context,
MaterialPageRoute(
builder: (context) => new Screen2(name: thing.name, email: thing.email, address: thing.address, etc..),
),
);
},
),
),
..
// screen2.dart
class Screen2 extends StatefulWidget{
Screen2({this.name, this.email, this.address, etc..});
final String name;
final String email;
final String address;
// etc
#override
State<StatefulWidget> createState() { return new Screen2State();}
}
class Screen2State extends State<Screen2> {
Widget build(BuildContext context) {
return new WillPopScope(
..
child: Scaffold(
..
new Row(
children: <Widget>[
new Text(widget.name),
new Text(widget.email),
new Text(widget.address),
etc..
],
),
)
)
}

You can pass argements through Map
arguments: {
"imageUrl": imageUrl,
"name": name,
"email": email
}
and you can receive like this
final data = ModalRoute.of(context)!.settings.arguments as Map;
String photoUrl = data["imageUrl"];

Related

using ChangeNotifier to add items into empty list

I already have data stored on firestore , but now i'd like to add this data into an empty list using ChangeNotifier , similar to this example -https://docs.flutter.dev/development/data-and-backend/state-mgmt/simple .
so below i'd like to add data stored on firebase into the _cart list , with the method I tried below I got the error The argument type 'List<Menu>' can't be assigned to the parameter type 'Menu'(would like to know why?) , it also contains the ui for where i'd like to map the data from cart list into the dialog sheet:
class AddList extends ConsumerWidget {
const AddList({Key? key}) : super(key: key);
#override
Widget build(BuildContext context, WidgetRef ref) {
final menuAsync = ref.watch(menuProvider);
final model = ref.read(cartProvider);
return Scaffold(
appBar: AppBar(
title: const Text("menu"),
),
floatingActionButton: FloatingActionButton(
backgroundColor: Colors.black,
onPressed: () async {
showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: const Text("cart"),
content: Column(
children: const [
...model.cart.map((item) => Text(item.mealName)),
],
),
);
});
},
),
body: menuAsync.when(
data: (menu) => Column(
children: menu
.map(
(e) => Card(
child: ListTile(
title: Text(e.mealName),
subtitle: Text(e.price),
trailing: IconButton(
onPressed: () {
model.addProduct(menu);//where im getting error
},
icon: const Icon(Icons.add)))),
)
.toList(),
),
error: (e, s) => Center(child: Text("$e")),
loading: () => const Center(child: CircularProgressIndicator())),
);
}
}
below im using changenotifier to modify the cart list:
final cartProvider =
ChangeNotifierProvider<CartNotifier>((ref) => CartNotifier());
class CartNotifier extends ChangeNotifier {
final List<Menu> _cart = [];
List<Menu> get cart => _cart;
void addProduct(Menu menu) {
_cart.add(menu);
notifyListeners();
}
void removeProduct(Menu menu) {
_cart.remove(menu);
notifyListeners();
}
}
how im reading data from firestore :
final menuProvider = StreamProvider<List<Menu>>(
(ref) => ref.read(addMealRespositoryProvider).menuSearchStream);
Stream<List<Menu>> get menuSearchStream =>
_firestore.collection("menu").snapshots().map(
(event) => event.docs.map((e) => Menu.fromFirestore(e)).toList(),
);
snippet of my data model:
class Menu {
String mealName;
String price;
Menu({
required this.mealName,
required this.price,
});
Map<String, dynamic> toMap() {
return {
"mealName": mealName,
"price": price, },
factory Menu.fromFirestore(DocumentSnapshot doc) {
final map = doc.data() as Map<String, dynamic>;
return Menu(
mealName: map["mealName"] ?? '',
price: map["price"] ?? '',
);
}
}

Loading listview from an api Layer

I am trying to load a listview using flutter and dart but am having an issue, bare with me am new to flutter and learning by example https://github.com/didinj/flutter-crud-restapi-example/blob/master/lib/caseslist.dart am coming from a c# background. I obfuscated my api url to protect it it is valid my side.
class PlayerList extends StatelessWidget {
final List<Player> players;
PlayerList({Key key, this.players}) : super(key: key);
#override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: players == null ? 0 : players.length,
itemBuilder: (BuildContext context, int index) {
return Card(
child: InkWell(
onTap: () {},
child: ListTile(
leading: Icon(Icons.person),
title: Text(players[index].firstName),
subtitle: Text(players[index].surname.toString()),
),
));
});
}
}
The issue surrounds this line.
PlayerList({Key key, this.players}) : super(key: key);
It says key does not exist.
I am loading the list view as such?.
#override
Widget build(BuildContext context) {
if (players == null) {
players = api.getAllPlayers() as List<Player>;
}
return Scaffold(
appBar: AppBar(
title: const Text("Flutter ListView"),
),
drawer: Drawer(
// Add a ListView to the drawer. This ensures the user can scroll
// through the options in the drawer if there isn't enough vertical
// space to fit everything.
child: new Center(
child: new FutureBuilder(
future: loadList(),
builder: (context, snapshot) {
return players.length > 0
? new PlayerList(players: players)
: new Center(
child: new Text('No data found, tap plus button to add!',
style: Theme.of(context).textTheme.titleLarge));
},
)),
));
}
Future loadList() {
Future<List<Player>> playersApi = api.getAllPlayers();
playersApi.then((PlayerList) {
setState(() {
this.players = PlayerList;
});
});
return playersApi;
}
}
My Api Call is
class ApiService {
final String apiUrl = "https://secreturl/api";
final String getAllPlayersEndPoint = "/GetAllPlayers/";
Future<List<Player>> getAllPlayers() async {
final getallPlayersUrl = Uri.parse(apiUrl + getAllPlayersEndPoint);
Response res = await get(getallPlayersUrl);
if (res.statusCode == 200) {
List<dynamic> body = jsonDecode(res.body);
List<Player> players =
body.map((dynamic item) => Player.fromJson(item)).toList();
return players;
} else {
throw "Failed to load cases list";
}
}
}
This is my Model
class Player {
final int id;
final int type;
final String playerLevel;
final String firstName;
final String surname;
Player(this.id, this.type, this.playerLevel, this.firstName, this.surname);
factory Player.fromJson(Map<String, dynamic> json) {
return Player(
json['id'],
json['type'],
json['playerlevel'],
json['firstname'],
json['surname'],
);
}
#override
String toString() =>
'Players{id: $id, firstName: $firstName, lastName: $surname}';
}

Flutter pass data to Statefulwidget

I need to know how can i pass data through the screens
Here is how I am sending data.
class _HomePageState extends State<HomePage> {
#override
initState() {
// TODO: implement initState
super.initState();
doSomeAsyncStuff();
}
Future<List> doSomeAsyncStuff() async {
final storage = new FlutterSecureStorage();
String value = await storage.read(key: 'Cnic');
print(value);
String url = 'http://api.igiinsurance.com.pk:8888/insurance_IgiGen/insurance-api/get_company_employee.php?offset=0&limit=1&cnic=${value}' ;
final msg = jsonEncode({"cnic": value});
Map<String,String> headers = {'Content-Type':'application/json'};
String token = value;
final response = await http.get(url);
var Data = json.decode(response.body);
print(Data);
var familyMembers = Data["records"][0]["family_members"];
print(familyMembers);
for (var familyMember in familyMembers){ //prints the name of each family member
var familyMemberName = familyMember["name"];
var familyMemberGender = familyMember["gender"];
var familyMemberAge = familyMember["age"];
var familyMemberRelationship = familyMember["relationship"];
print(familyMemberName);
}
}
#override
Widget build(BuildContext context) {
double statusBarHeight = MediaQuery.of(context).padding.top;
double width = MediaQuery.of(context).size.width;
double height = MediaQuery.of(context).size.height;
return Scaffold(
appBar: AppBar(
centerTitle: true,
automaticallyImplyLeading: false,
title: Text('IGI GENERAL INSURANCE'),
),
body: Center(
child: GestureDetector(
onTap: (){
Navigator.push(
context,
MaterialPageRoute(builder: (context) => PersonalPage(familyMemberName, familyMemberGender)),
);
},
child: Column(
children: <Widget>[
ClipRRect(
borderRadius: BorderRadius.circular(35),
child: Image(
image: AssetImage("assets/images/reg.png"),
height: height * 0.1,
)),
Text(
'Personal',
style: TextStyle(
fontSize: 17, fontWeight: FontWeight.bold),
)
],
),
),
)
);
}
}
This is how i am sending the values
onTap: (){
Navigator.push(
context,
MaterialPageRoute(builder: (context) => PersonalPage(familyMemberName,
familyMemberGender)),
);}
Now i want to show the value in a other stateful widget
class PersonalPage extends StatefulWidget {
#override
_PersonalPageState createState() => _PersonalPageState();
}
class _PersonalPageState extends State<PersonalPage> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: <Widget>[
Text('Show name here '),
Text('Show gender here ')
],
),
);
}
}
As you can see i have values i am passing to the other stateful widget. I need to show the value now in Text Widget
Added _homeState also in a question now
You can receive the values by using the constructor of the PersonalPage class:
import "package:flutter/material.dart";
class PersonalPage extends StatefulWidget {
final List<String> names;
final List<String> genders;
PersonalPage(this.names,this.genders);
#override
_PersonalPageState createState() => _PersonalPageState();
}
class _PersonalPageState extends State<PersonalPage> {
#override
Widget build(BuildContext context) {
return Scaffold(
body:
ListView.builder( //use ListView here to show all the names and genders
itemCount: widget.names.length,
itemBuilder: (BuildContext context,int index){
return ListTile(
title: Text(widget.names[index]),
subtitle: Text(widget.genders[index])
],
);
})
);
}
}
Your _HomePageState should look like this:
class _HomePageState extends State<HomePage> {
//define your variables here so they are accessible throughout your widget tree
List<String> familyMemberName = [];
List<String> familyMemberGender = [];
List<String> familyMemberAge = [];
List<String> familyMemberRelationship = [];
#override
initState() {
// TODO: implement initState
super.initState();
doSomeAsyncStuff();
}
Future<List> doSomeAsyncStuff() async {
final storage = new FlutterSecureStorage();
String value = await storage.read(key: 'Cnic');
print(value);
String url = 'http://api.igiinsurance.com.pk:8888/insurance_IgiGen/insurance-api/get_company_employee.php?offset=0&limit=1&cnic=${value}' ;
final msg = jsonEncode({"cnic": value});
Map<String,String> headers = {'Content-Type':'application/json'};
String token = value;
final response = await http.get(url);
var Data = json.decode(response.body);
print(Data);
var familyMembers = Data["records"][0]["family_members"];
print(familyMembers);
for (var familyMember in familyMembers){ //prints the name of each family member
//assign the values here
familyMemberName.add(familyMember["name"]);
familyMemberGender.add(familyMember["gender"]);
familyMemberAge.add(familyMember["age"]);
familyMemberRelationship.add(familyMember["relationship"]);
}
}
#override
Widget build(BuildContext context) {
double statusBarHeight = MediaQuery.of(context).padding.top;
double width = MediaQuery.of(context).size.width;
double height = MediaQuery.of(context).size.height;
return Scaffold(
appBar: AppBar(
centerTitle: true,
automaticallyImplyLeading: false,
title: Text('IGI GENERAL INSURANCE'),
),
body: Center(
child: GestureDetector(
onTap: (){
if(familyMemberName.isNotEmpty() && familyMemberGender.isNotEmpty()){
//we pass the lists here
Navigator.push(
context,
MaterialPageRoute(builder: (context) => PersonalPage(familyMemberName, familyMemberGender)),
}
//only navigate to the new page if the values of familyMemberName and familyMemberGender are retrieved from the function(because your function returns a future so it might take sometimes before the values are assigned)
);
},
child: Column(
children: <Widget>[
ClipRRect(
borderRadius: BorderRadius.circular(35),
child: Image(
image: AssetImage("assets/images/reg.png"),
height: height * 0.1,
)),
Text(
'Personal',
style: TextStyle(
fontSize: 17, fontWeight: FontWeight.bold),
)
],
),
),
)
);
}
}

How to get the specific data through api by using flutter_bloc

I am beginner in flutter and working on fetching the specific data by using flutter_bloc package. I have successfully fetch the api data by using flutter_bloc in HomePage but how do i fetch the more specific data.For example in Home Page it fetch the data when i open the app and there is a button at the bottom which moves to new screen that is a Settings Screen which has Two radio buttons and one Raised Button named as Save.When i select any of the radiobutton and click on save button it should moves back to the homepage and calls the api and update the data which was already fetched in homepage. Below is the dart code and bloc code, it will be lengthy but hope you understand my code
Main.dart
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MultiBlocProvider(
providers: [
BlocProvider<PrayerBloc>(
create: (BuildContext context) => PrayerBloc(repository: PrayerRepositoryImpl()),
),
BlocProvider<MethodBloc>(
create: (BuildContext context) => MethodBloc(methodRepository: MethodRepositoryImpl()),
),
],
child: HomePage(),
);
HomePage.dart
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
PrayerBloc prayerBloc;
#override
void initState() {
super.initState();
prayerBloc = BlocProvider.of<PrayerBloc>(context);
prayerBloc.add(FetchPrayerEvent());
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Builder(
builder: (context) {
return Material(
child: Scaffold(
appBar: AppBar(
title: Text("Prayer API"),
),
body: Container(
child: BlocListener<PrayerBloc, PrayerState>(
listener: (context, state) {
if (state is PrayerErrorState) {
Scaffold.of(context).showSnackBar(
SnackBar(
content: Text(state.message),
),
);
}
},
child: BlocBuilder<PrayerBloc, PrayerState>(
builder: (context, state) {
if (state is InitialPrayerState) {
return buildLoading();
} else if (state is PrayerLoadingState) {
return buildLoading();
} else if (state is PrayerLoadedState) {
return buildArticleList(state.item);
} else if (state is PrayerErrorState) {
return buildErrorUi(state.message);
}
},
),
),
),
),
);
},
),
);
}
Widget buildLoading() {
return Center(
child: CircularProgressIndicator(),
);
}
Widget buildErrorUi(String message) {
return Center(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
message,
style: TextStyle(color: Colors.red),
),
),
);
}
Widget buildArticleList(List<Item> item) {
return ListView.builder(
itemCount: item == null ? 0 : item.length,
itemBuilder: (BuildContext ctx, int pos) {
return new Container(
child: new Center(
child: new Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
new Card(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: new Container(
child: Column(
children: <Widget>[
Padding(
padding: EdgeInsets.only(top: 10.0),
),
Row(
children: <Widget>[
Text("Fajr"),
Padding(
padding: EdgeInsets.only(left: 50.0),
),
Text(item[pos].fajr),
],
),
Row(
children: <Widget>[
Text("Dhuhr"),
Padding(
padding: EdgeInsets.only(left: 30.0),
),
Text(item[pos].dhuhr),
],
),
Builder(
builder: (context)=>
RaisedButton(
onPressed: (){
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SettingsPage()),
);
},
),
)
],
),
),
),
)
],
),
),
);
},
);
}
Prayer_bloc.dart
class PrayerBloc extends Bloc<PrayerEvent, PrayerState> {
PrayerRepository repository;
PrayerBloc({#required this.repository});
#override
PrayerState get initialState => InitialPrayerState();
#override
Stream<PrayerState> mapEventToState(
PrayerEvent event,
) async* {
if (event is FetchPrayerEvent) {
yield PrayerLoadingState();
try {
List<Item> item = await repository.getItem();
yield PrayerLoadedState(item: item);
} catch (e) {
yield PrayerErrorState(message: e.toString());
}
}
}
}
PrayerEvent.dart
abstract class PrayerEvent extends Equatable {}
class FetchPrayerEvent extends PrayerEvent {
#override
// TODO: implement props
List<Object> get props => null;
}
PrayerState.dart
abstract class PrayerState extends Equatable {
const PrayerState();
}
class InitialPrayerState extends PrayerState {
#override
List<Object> get props => [];
}
class PrayerLoadingState extends PrayerState {
#override
List<Object> get props => [];
}
class PrayerLoadedState extends PrayerState {
List<Item> item;
PrayerLoadedState({#required this.item});
#override
List<Object> get props => null;
}
class PrayerErrorState extends PrayerState {
String message;
PrayerErrorState({#required this.message});
#override
List<Object> get props => [message];
}
PrayerRepository.dart
abstract class PrayerRepository {
Future<List<Item>> getItem();
}
class PrayerRepositoryImpl implements PrayerRepository {
#override
Future<List<Item>> getItem() async {
var response = await http.get("https://muslimsalat.com/riyadh.json?key=");
if (response.statusCode == 200) {
var data = json.decode(response.body);
List<Item> item = Welcome.fromJson(data).items;
return item;
} else {
throw Exception();
}
}
}
So these dart code fetch the data from api and load in HomePage when i open the application.Now the second page which is settings page, below is the code
SettingsPage.dart
class SettingsPage extends StatefulWidget {
#override
_SettingsPageState createState() => _SettingsPageState();
}
class _SettingsPageState extends State<SettingsPage> {
int selectedRadio;
#override
void initState() {
super.initState();
selectedRadio=0;
}
setSelectedRadio(int val){
setState(() {
selectedRadio=val;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Container(
child: ListView(
children: <Widget>[
BlocBuilder<MethodBloc,MethodState>(
builder: (context,state){
return Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Container(
padding: EdgeInsets.all(15.0),
child: Text(
"Prayer Methods",
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
),
Column(
children: <Widget>[
RadioListTile(
value: 1,
groupValue: selectedRadio,
activeColor: Colors.black,
title: Text(
"Egyptian General Authority of Survey",
),
onChanged: (val) {
print(val);
setSelectedRadio(val);
}),
RadioListTile(
value: 2,
groupValue: selectedRadio,
activeColor: Colors.black,
title: Text(
"University Of Islamic Sciences, Karachi (Shafi)",
),
onChanged: (val) {
print(val);
setSelectedRadio(val);
}),
FloatingActionButton(
onPressed: (){
Navigator.pop(context);
BlocProvider.of<MethodBloc>(context).add(MethodChangedEvent(method: selectedRadio)); //I have try this code in onpressed but unfortunately not succeed
print(selectedRadio);
},
child: Text('Save')
)
],
),
],
);
},
)
],
),
),
);
}
}
MethodBloc.dart
class MethodBloc extends Bloc<MethodEvent, MethodState> {
MethodRepository methodRepository;
MethodBloc({#required this.methodRepository});
#override
MethodState get initialState => InitialMethodState();
#override
Stream<MethodState> mapEventToState(
MethodEvent event,
) async* {
if(event is MethodChangedEvent){
yield MethodLoadingState();
try {
List<Item> item = await methodRepository.getMethod(event.method);
yield MethodLoadedState(item: item);
} catch (e) {
yield MethodErrorState(message: e.toString());
}
}
}
}
MethodEvent.dart
abstract class MethodEvent extends Equatable {
const MethodEvent();
}
class MethodChangedEvent extends MethodEvent {
final int method;
MethodChangedEvent({this.method}) : assert(method != null);
#override
List<Object> get props => null;
}
MethodState.dart
abstract class MethodState extends Equatable {
const MethodState();
}
class InitialMethodState extends MethodState {
#override
List<Object> get props => [];
}
class MethodLoadingState extends MethodState {
#override
List<Object> get props => [];
}
class MethodLoadedState extends MethodState {
List<Item> item;
MethodLoadedState({#required this.item});
#override
List<Object> get props => null;
}
class MethodErrorState extends MethodState {
String message;
MethodErrorState({#required this.message});
#override
List<Object> get props => [message];
}
MethodRepository.dart
abstract class MethodRepository{
Future<List<Item>> getMethod(int method);
}
class MethodRepositoryImpl implements MethodRepository {
#override
Future<List<Item>> getMethod(int method) async {
var response = await http.get("https://muslimsalat.com/riyadh/$method.json?key=");
if (response.statusCode == 200) {
var data = json.decode(response.body);
List<Item> item = Welcome.fromJson(data).items;
return item;
} else {
throw Exception();
}
}
}
PrayerModel.dart
class Welcome {
String title;
String query;
String welcomeFor;
int method;
String prayerMethodName;
String daylight;
String timezone;
String mapImage;
String sealevel;
TodayWeather todayWeather;
String link;
String qiblaDirection;
String latitude;
String longitude;
String address;
String city;
String state;
String postalCode;
String country;
String countryCode;
List<Item> items;
int statusValid;
int statusCode;
String statusDescription;
Welcome({
this.title,
this.query,
this.welcomeFor,
this.method,
this.prayerMethodName,
this.daylight,
this.timezone,
this.mapImage,
this.sealevel,
this.todayWeather,
this.link,
this.qiblaDirection,
this.latitude,
this.longitude,
this.address,
this.city,
this.state,
this.postalCode,
this.country,
this.countryCode,
this.items,
this.statusValid,
this.statusCode,
this.statusDescription,
});
factory Welcome.fromJson(Map<String, dynamic> json) => Welcome(
title: json["title"],
query: json["query"],
welcomeFor: json["for"],
method: json["method"],
prayerMethodName: json["prayer_method_name"],
daylight: json["daylight"],
timezone: json["timezone"],
mapImage: json["map_image"],
sealevel: json["sealevel"],
todayWeather: TodayWeather.fromJson(json["today_weather"]),
link: json["link"],
qiblaDirection: json["qibla_direction"],
latitude: json["latitude"],
longitude: json["longitude"],
address: json["address"],
city: json["city"],
state: json["state"],
postalCode: json["postal_code"],
country: json["country"],
countryCode: json["country_code"],
items: List<Item>.from(json["items"].map((x) => Item.fromJson(x))),
statusValid: json["status_valid"],
statusCode: json["status_code"],
statusDescription: json["status_description"],
);
Map<String, dynamic> toJson() => {
"title": title,
"query": query,
"for": welcomeFor,
"method": method,
"prayer_method_name": prayerMethodName,
"daylight": daylight,
"timezone": timezone,
"map_image": mapImage,
"sealevel": sealevel,
"today_weather": todayWeather.toJson(),
"link": link,
"qibla_direction": qiblaDirection,
"latitude": latitude,
"longitude": longitude,
"address": address,
"city": city,
"state": state,
"postal_code": postalCode,
"country": country,
"country_code": countryCode,
"items": List<dynamic>.from(items.map((x) => x.toJson())),
"status_valid": statusValid,
"status_code": statusCode,
"status_description": statusDescription,
};
}
class Item {
String dateFor;
String fajr;
String shurooq;
String dhuhr;
String asr;
String maghrib;
String isha;
Item({
this.dateFor,
this.fajr,
this.shurooq,
this.dhuhr,
this.asr,
this.maghrib,
this.isha,
});
factory Item.fromJson(Map<String, dynamic> json) => Item(
dateFor: json["date_for"],
fajr: json["fajr"],
shurooq: json["shurooq"],
dhuhr: json["dhuhr"],
asr: json["asr"],
maghrib: json["maghrib"],
isha: json["isha"],
);
Map<String, dynamic> toJson() => {
"date_for": dateFor,
"fajr": fajr,
"shurooq": shurooq,
"dhuhr": dhuhr,
"asr": asr,
"maghrib": maghrib,
"isha": isha,
};
}
class TodayWeather {
int pressure;
String temperature;
TodayWeather({
this.pressure,
this.temperature,
});
factory TodayWeather.fromJson(Map<String, dynamic> json) => TodayWeather(
pressure: json["pressure"],
temperature: json["temperature"],
);
Map<String, dynamic> toJson() => {
"pressure": pressure,
"temperature": temperature,
};
}
Once you've defined the Model for the Stream in bloc, you can easily access the object using BlocBuilder. As demonstrated on the code you've shared, you're able to build a List with buildArticleList() from the Stream. To access a specific data, you can follow a similar approach for that object.

Unable to display string from snapshot

I would like to get data from firestore and display in the text but an eror has popup.
Thar error say type '_BroadcsastStream' is not a subtype of type 'String'.
Class i call the method
void main() => runApp(MaterialApp(
home : profUser(),
));
class profUser extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
home : new profiUser(),
);
}
}
class profiUser extends StatefulWidget {
#override
_profiUserState createState() => _profiUserState();
}
class _profiUserState extends State<profiUser> {
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.indigo,
appBar: AppBar(
title: Text('Profile'),
actions: <Widget>[
IconButton(
icon: Icon(choices[1].icon),
onPressed: (){
logOut();
Navigator.push(context,MaterialPageRoute(builder: (context)
=> myLogin()));
},
),
],
),
body: Column(
children: <Widget>[
userDetail(),
],
),
);
}
}
Class to display text based on the data from firestore
class userDetail extends StatelessWidget{
#override
Widget build(BuildContext context){
return new StreamBuilder(
stream: UniQuery().getUserDetail(),
builder: (BuildContext context, snapshot){
if(!snapshot.hasData)
return new Text('Loading..... Please wait');
var userDocument = snapshot.data;
return new Column(
children: <Widget>[
Text('Name: ' + userDocument['name']),
Text('Age: ' + userDocument['age'],toString()),
Text('Address: ' + userDocument['address']),
Text('Result: ' + userDocument['result']),
],
);
}
);
}
}
Below the void that use in above code to get data from firestore
var userID;
Future<String> getCurrentUser() async{
final FirebaseUser user = await FirebaseAuth.instance.currentUser();
// return uID != null ? uID : null;
final String uID = user.uid.toString();
return uID;
}
setUserDetail() async{
userID = await getCurrentUser();
}
The problem is inside getUserDetail() you are passing an async function to documents(), so that function returns a Future. Before calling documents() you should first get the string, waiting the async call to finish, and then pass the string to documents().