how to get data from api(Map type) for dropdown option - android

I have a problem when i want to get data from api and show them in dropdown option, I can print data when i run my code but in dropdown option i have below error :
type '(dynamic) => DropdownMenuItem' is not a subtype of type '(String, dynamic) => MapEntry' of 'transform'
import 'package:flutter/material.dart';
import 'package:dropdownfield/dropdownfield.dart';
import 'package:http/http.dart' as http;
import 'dart:async';`enter code here`
import 'dart:convert';
class InBoundRate extends StatefulWidget {
#override
_InBoundRateState createState() => _InBoundRateState();
}
class _InBoundRateState extends State<InBoundRate> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: new Center(
child: new FutureBuilder(
future: GetInbound(),
builder: (BuildContext context, AsyncSnapshot<Map> snapshot) {
if (snapshot.hasData) {
Map content = snapshot.data ;
var sampleData = json.encode(content);
var json2 = JsonDecoder().convert(sampleData);
// print(json2['data']['countries']);
return DropdownButton(
items: json2.map(
(item) => DropdownMenuItem(
value: item['data']['countries'],
child: Text(item['data']['countries'])),
// onChanged: (Users value) {
// setState(() {
// _currentUser = value;
// });
// }
),
isExpanded: false,
//value: _currentUser,
hint: Text('Select User'),
);
} else {
return new Container();
}
}),
),
);
}
}
Future<Map> GetInbound() async {
String apiUrl = 'http://homaexpressco.ir/api/getRatesInformation2';
http.Response response = await http.get(apiUrl);
var res = json.decode(response.body);
return res;
}

Related

How to get the map data from the DocumentSnapshot, and get the field name?

Here are my current code and output.
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
class MedicalConditionList extends StatefulWidget {
const MedicalConditionList({Key? key}) : super(key: key);
#override
State<MedicalConditionList> createState() => _MedicalConditionListState();
}
class _MedicalConditionListState extends State<MedicalConditionList> {
final Stream<DocumentSnapshot> _medicalConditionStream = FirebaseFirestore
.instance
.collection('medical_condition')
.doc('b3936f64-8d90-4')
.snapshots();
List trueMedical = [];
bool contains = true;
#override
Widget build(BuildContext context) {
return StreamBuilder<DocumentSnapshot>(
stream: _medicalConditionStream,
builder: (context, AsyncSnapshot<DocumentSnapshot> snapshot) {
if (snapshot.hasError) {
return const Center(child: Text('Something went wrong'));
}
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(
child: CircularProgressIndicator(
color: Colors.red,
),
);
}
if (snapshot.connectionState == ConnectionState.active) {
var condition = snapshot.data?.data();
return Text(condition.toString());
}
return Container();
},
);
}
}
Output:
I have the data her but how can I do a listView of just the data with value of true, instead of print a whole bunch of data from my firebase.
I am thinking if I have a way to just get specific data like asthma when it is true by doing a map search such as
void main() {
var condition = {"asthma": true, "liver": false'};
usrMap.forEach((k,v) {
if(v == true){
print(k)
}
});
}
Something like this, maybe I am wrong. Main point is how to get just specific data.

how to pass array of data from API into graph in flutter?

I have an issue while integrating an array of data from API into my graph, I have tried all other methods but I don't find any solution. How to Use model class to get API data and integrate it into a graph.
import 'dart:convert';
import 'package:chartapp/network/network_helper.dart';
import 'package:chartapp/src/Bar_Chart/bar_model.dart';
import 'package:flutter/material.dart';
import 'package:charts_flutter/flutter.dart' as charts;
import 'package:http/http.dart' as http;
import 'gender_model.dart';
class NetworkHelper {
Future<http.Response> post(String endpoint) async {
var url = Uri.parse(endpoint);
var response = await http.post(url, headers: {
'Authorization':
'token',
'Cookie': ''
});
return response;
}
}
class BarChartAPI extends StatefulWidget {
const BarChartAPI({Key? key}) : super(key: key);
#override
State<BarChartAPI> createState() => _BarChartAPIState();
}
class _BarChartAPIState extends State<BarChartAPI> {
List<Graphmodel> graph = [];
bool loading = true;
NetworkHelper _networkHelper = NetworkHelper();
#override
void initState() {
super.initState();
getData();
}
void getData() async {
var response = await _networkHelper.post(
"*********************************");
final tempdata = json.decode(response.body)['result']["meter"]
["performance"]["growth"]["graph-data"];
List data = tempdata
.map((e) => Graphmodel(name: e['name'], value: e['value']))
.toList();
print(tempdata);
print(data);
setState(() {
graph = data as List<Graphmodel>;
loading = false;
});
}
List<charts.Series<Graphmodel, String>> _createSampleData() {
return [
charts.Series<Graphmodel, String>(
data: graph ,
id: 'graph_data',
colorFn: (_, __) => charts.MaterialPalette.teal.shadeDefault,
domainFn: (Graphmodel graphmodel, _) => graphmodel.name,
measureFn: (Graphmodel graphmodel, _) => graphmodel.value,
)
];
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Graph"),
),
body: Center(
child: loading
? CircularProgressIndicator()
: Container(
height: 300,
child: charts.BarChart(
_createSampleData(),
animate: true,
),
),
),
);
}
}
This is my console response
[1]: https://i.stack.imgur.com/Hkomh.png
The following is my class model
import 'dart:convert';
List<Graphmodel> graphmodelFromJson(String str) =>
List<Graphmodel>.from(json.decode(str).map((x) => Graphmodel.fromJson(x)));
String graphmodelToJson(List<Graphmodel> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Graphmodel {
Graphmodel({
required this.name,
required this.value,
});
String name;
int value;
factory Graphmodel.fromJson(Map<String, dynamic> json) => Graphmodel(
name: json["name"],
value: json["value"],
);
Map<String, dynamic> toJson() => {
"name": name,
"value": value,
};
}

DialogFlow Chatbot not showing the output

I am integrating DialogFlowtter the DialogFlow package of Google Cloud. It is not outputting any data to the screen PLease look into my code and help me out. Any hep would be aprreciated. Actually the code runs properly but when the if condition is check instead of hasdata it goes into haserror and just print "Error"
import 'dart:math';
import 'package:dialog_flowtter/dialog_flowtter.dart';
import 'package:flutter/material.dart';
class ChatBot extends StatefulWidget {
const ChatBot({Key? key}) : super(key: key);
#override
_ChatBotState createState() => _ChatBotState();
}
class _ChatBotState extends State<ChatBot> {
late DialogFlowtter? instance;
DialogAuthCredentials? credentials;
String? num;
getRandomSessionID() {
num = Random().nextInt(1000).toString();
}
getCred() async {
credentials =
await DialogAuthCredentials.fromFile('assets/credentials.json');
}
#override
void initState() {
// TODO: implement initState
getCred();
getRandomSessionID();
super.initState();
}
getQuery() async {
instance = DialogFlowtter(credentials: credentials!, sessionId: num!);
final QueryInput queryInput = QueryInput(
text: TextInput(
text: "Hi. How are you?",
languageCode: "en",
),
);
DetectIntentResponse response = await instance!.detectIntent(
queryInput: queryInput,
);
//print(response);
return response.text;
}
#override
Widget build(BuildContext context) {
return Column(
children: [
//Text(getQuery()),
Center(
child: FutureBuilder<dynamic>(
future: getQuery(),
builder: (
BuildContext context,
AsyncSnapshot<dynamic> snapshot,
) {
if (snapshot.connectionState == ConnectionState.waiting)
return Center(child: CircularProgressIndicator());
else if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasError)
return Center(child: const Text('Error'));
else if (snapshot.hasData)
return Center(child: Text(snapshot.data!));
else {
return const Text('Empty data');
}
} else {
return Text('State: ${snapshot.connectionState}');
}
},
),
),
],
);
}
}

The getter 'pokemon' was called on null

I am trying to make a pokemon app. But I get this error:
"The getter 'pokemon' was called on null.
Receiver: null
Tried calling: pokemon"
I am using this API url for data "https://raw.githubusercontent.com/Biuni/PokemonGO-Pokedex/master/pokedex.json"
And my Pokemon class is here:
class PokeHub {
List<Pokemon> pokemon;
PokeHub({this.pokemon});
PokeHub.fromJson(Map<String,dynamic> json) {
if (json['pokemon'] != null) {
pokemon = new List<Pokemon>();
json['pokemon'].forEach((items) {
pokemon.add(new Pokemon.fromJson(items));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.pokemon != null) {
data['pokemon'] = this.pokemon.map((items) => items.toJson()).toList();
}
return data;
}
}
class Pokemon {
int id;
String num;
String name;
String img;
List<String> type;
String height;
String weight;
String candy;
int candyCount;
String egg;
String spawnChance;
String avgSpawns;
String spawnTime;
List<double> multipliers;
List<String> weaknesses;
List<NextEvolution> nextEvolution;
Pokemon(
{this.id,
this.num,
this.name,
this.img,
this.type,
this.height,
this.weight,
this.candy,
this.candyCount,
this.egg,
this.spawnChance,
this.avgSpawns,
this.spawnTime,
this.multipliers,
this.weaknesses,
this.nextEvolution});
Pokemon.fromJson(Map<String, dynamic> json) {
id = json['id'];
num = json['num'];
name = json['name'];
img = json['img'];
type = json['type'].cast<String>();
height = json['height'];
weight = json['weight'];
candy = json['candy'];
candyCount = json['candy_count'];
egg = json['egg'];
spawnChance = json['spawn_chance'].toString();
avgSpawns = json['avg_spawns'].toString();
spawnTime = json['spawn_time'];
multipliers = json['multipliers']?.cast<double>();
weaknesses = json['weaknesses'].cast<String>();
if (json['next_evolution'] != null) {
nextEvolution = new List<NextEvolution>();
json['next_evolution'].forEach((v) {
nextEvolution.add(new NextEvolution.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['num'] = this.num;
data['name'] = this.name;
data['img'] = this.img;
data['type'] = this.type;
data['height'] = this.height;
data['weight'] = this.weight;
data['candy'] = this.candy;
data['candy_count'] = this.candyCount;
data['egg'] = this.egg;
data['spawn_chance'] = this.spawnChance;
data['avg_spawns'] = this.avgSpawns;
data['spawn_time'] = this.spawnTime;
data['multipliers'] = this.multipliers;
data['weaknesses'] = this.weaknesses;
if (this.nextEvolution != null) {
data['next_evolution'] =
this.nextEvolution.map((v) => v.toJson()).toList();
}
return data;
}
}
class NextEvolution {
String num;
String name;
NextEvolution({this.num, this.name});
NextEvolution.fromJson(Map<String, dynamic> json) {
num = json['num'];
name = json['name'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['num'] = this.num;
data['name'] = this.name;
return data;
}
And this is my main.dart file:
import 'package:flutter/material.dart';
import 'package:pokemon_flutter/screens/main_screen.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: "Poke App",
home: MainScreen(),
debugShowCheckedModeBanner: false,
);
}
}
And this is my main_screen.dart file:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:pokemon_flutter/models/pokemon.dart';
class MainScreen extends StatefulWidget {
#override
_MainScreenState createState() => _MainScreenState();
}
class _MainScreenState extends State<MainScreen> {
var url =
"https://raw.githubusercontent.com/Biuni/PokemonGO-Pokedex/master/pokedex.json";
PokeHub pokeHub;
#override
void initState() {
super.initState();
fetchData();
}
void fetchData() async {
var res = await http.get(url);
var decodedJson = jsonDecode(res.body);
pokeHub = PokeHub.fromJson(decodedJson);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Poke App"),
backgroundColor: Colors.cyan,
),
body: GridView.count(
crossAxisCount: 2,
children: pokeHub.pokemon.map((poke) => Card()).toList(),
),
drawer: Drawer(),
floatingActionButton: FloatingActionButton(
onPressed: () {},
backgroundColor: Colors.cyan,
child: Icon(Icons.refresh),
),
);
}
}
It seems like all things are true thats why I can not recognized the fault. If you have a advice for this situation I'll be appreciated.
Edit: I am new here thats why sometimes my questions could be meanless.But please dont decrease my points. Stackoverflow not gonna accept my questions anymore. Please increase my points.
when I finished my code the aplication worked. Here is my new main_screen.dart file:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:pokemon_flutter/models/pokemon.dart';
import 'package:pokemon_flutter/screens/pokemon_detail_screen.dart';
class MainScreen extends StatefulWidget {
#override
_MainScreenState createState() => _MainScreenState();
}
class _MainScreenState extends State<MainScreen> {
var url =
"https://raw.githubusercontent.com/Biuni/PokemonGO-Pokedex/master/pokedex.json";
PokeHub pokeHub;
#override
void initState() {
super.initState();
fetchData();
}
var res;
void fetchData() async {
res= await http.get(url);
var decodedJson = jsonDecode(res.body);
pokeHub = PokeHub.fromJson(decodedJson);
print(pokeHub.toJson());
setState(() {});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Poke App"),
backgroundColor: Colors.cyan,
),
body: pokeHub == null
? Center(
child: CircularProgressIndicator(),
)
: GridView.count(
crossAxisCount: 2,
children: pokeHub.pokemon
.map((poke) => Padding(
padding: const EdgeInsets.all(2.0),
child: InkWell(
onTap: (){
Navigator.push(context, MaterialPageRoute(builder: (context)=>PokeDetail(
pokemon: poke,
)));
},
child: Hero(
tag: poke.img,
child: Card(
elevation: 3.0,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Container(
height: 100.0,
width: 100.0,
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage(poke.img))),
),
Text(
poke.name,
style: TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.bold,
),
)
],
),
),
),
),
))
.toList(),
),
drawer: Drawer(),
floatingActionButton: FloatingActionButton(
onPressed: () {},
backgroundColor: Colors.cyan,
child: Icon(Icons.refresh),
),
);
}
}
I added if else statement and set state. I don't know how I solved this problem but it was solved.
I think this codes are worked:
void fetchData() async {
res= await http.get(url);
var decodedJson = jsonDecode(res.body);
pokeHub = PokeHub.fromJson(decodedJson);
print(pokeHub.toJson());
setState(() {});
}
body: pokeHub == null
? Center(
child: CircularProgressIndicator(),
)
: GridView.count(
When you call pokeHub.pokemon, pokeHub is still null so it can't return any value for pokemon getter.
I see that you are fetching data, but when your widget is built, this data (which is returned asynchronously) hasn't been returned yet. For this case, it will be a good choice using FutureBuilder. Something like this should work:
var res;
void fetchData() {
res = http.get(url).then((value){
var decodedJson = jsonDecode(res.body);
pokeHub = PokeHub.fromJson(decodedJson);
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Poke App"),
backgroundColor: Colors.cyan,
),
body: FutureBuilder(
future: res,
builder: (BuildContext context, AsyncSnapshot snapshot) {
if(snapshot.hasData)
return GridView.count(
crossAxisCount: 2,
children: pokeHub.pokemon.map((poke) => Card()).toList(),
),
drawer: Drawer(),
floatingActionButton: FloatingActionButton(
onPressed: () {},
backgroundColor: Colors.cyan,
child: Icon(Icons.refresh),
);
},
),
);
}
This (kind of) uses the futurebuilder to build the widgets only once the data has been retrieved. More info: https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html

A non-null String must be provided to a Text widget. 'package:flutter/src/widgets/text.dart': Failed assertion: line 360 pos 10: 'data != null'

Flutter Error : A non-null String must be provided to a Text widget. 'package:flutter/src/widgets/text.dart': Failed assertion: line 360 pos 10: 'data != null'
Another exception was thrown: A non-null String must be provided to a Text widget.
This is Main.dart
import 'package:bheekho_foundation/widgets/app.dart';
import 'package:flutter/material.dart';
void main() {
runApp(App());
}
This is App.dart
import 'package:bheekho_foundation/screens/home.dart';
import 'package:flutter/material.dart';
class App extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: HomeScreen(),
);
}
}
This is Home.dart
import 'dart:convert';
import 'package:bheekho_foundation/models/request.dart';
import 'package:bheekho_foundation/services/request_service.dart';
import 'package:flutter/material.dart';
class HomeScreen extends StatefulWidget {
#override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
RequestService _requestService = RequestService();
// ignore: unused_element
Future<List<Request>> _getAllRequest() async {
var result = await _requestService.getAllRequests();
List<Request> _list = List<Request>();
if (result != null) {
var requests = json.decode(result.body);
requests.forEach((request) {
var model = Request();
model.user_id = request['user_id'];
model.concern = request['concern'];
model.message = request['message'];
setState(() {
_list.add(model);
});
});
}
return _list;
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Bheekho App"),
),
body: FutureBuilder<List<Request>>(
future: _getAllRequest(),
builder:
(BuildContext context, AsyncSnapshot<List<Request>> snapshot) {
if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
return Column(
children: [
Card(
child: Text(snapshot.data[index].user_id),
),
],
);
});
} else {
return Container(
child: Text('loading...'),
);
}
},
));
}
}
This is my Model request.dart
class Request {
// ignore: non_constant_identifier_names
int request_id;
// ignore: non_constant_identifier_names
String user_id;
String concern;
String message;
}
This is Request_Service.dart
import 'package:bheekho_foundation/repository/repository.dart';
class RequestService {
Repository _repository;
RequestService() {
_repository = Repository();
}
getAllRequests() async {
return await _repository.httpGet('users');
}
}
This is Repository.dart
import 'package:http/http.dart' as http;
class Repository {
String _baseUrl = "http://localhost:8000/api";
httpGet(String api) async {
return await http.get(_baseUrl + "/" + api);
}
}
Erorr ScreenShot
Your snapshot.data[index].user_id is most likely null at this point.
To make sure you do not assign null to a Text widget, you can change it to something like this:
Text(
snapshot.data[index].user_id != null
? snapshot.data[index].user_id
: ""
)
This actually checks if the data is null, when it's not, it loads the snapshot data. In case it is, it loads an empty string.

Categories

Resources