checking if a long sentence contains a short sentence from TextField, Dart - android

I want to search for a short sentence inside a long sentence ...
it is working fine with this demo:
String a = 'from first day i was very good';
String b = 'from first day';
print(a.contains(b));
result : true
but when I use TextField to enter a short sentence and check it if is exciting in a long sentence ...
TextField when I enter space between words doesn't show any result
Note: this app in the Arabic language and doesn't work on an android and IOS ... in English worked well in the IOS simulator but doesn't work on an android phone.
my all code:
import 'dart:convert';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:egyptian_ads_app/constant/constant.dart';
import 'package:egyptian_ads_app/pages/business_man_pages/business_man_page.dart';
import 'package:egyptian_ads_app/pages/starting_page/landing_service_page.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:share/share.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:url_launcher/url_launcher.dart';
class ItemModel {
ItemModel(
{this.id,
this.title,
this.imagePath,
this.about,
this.phoneNumber,
this.traderId,
this.type,
this.city});
int id;
String title;
String imagePath;
String about;
String phoneNumber;
int traderId;
String type;
String city;
factory ItemModel.fromJson(Map<String, dynamic> json) {
return new ItemModel(
id: json['id'],
title: json['name'],
imagePath: json["logo"]['url'],
about: json['about'],
phoneNumber: json['phone_number'],
traderId: json['trader_id'],
type: json['category']['type'],
// city: json['city'],
);
}
}
class InstantSearchPage extends StatefulWidget {
#override
_InstantSearchPageState createState() => _InstantSearchPageState();
}
class _InstantSearchPageState extends State<InstantSearchPage> {
TextEditingController _searchController = TextEditingController();
Future resultsLoaded;
List<ItemModel> _allResults = [];
List<ItemModel> _resultsList = [];
#override
void initState() {
super.initState();
_searchController.addListener(_onSearchChanged);
}
#override
void dispose() {
_searchController.removeListener(_onSearchChanged);
_searchController.dispose();
super.dispose();
}
#override
void didChangeDependencies() {
super.didChangeDependencies();
resultsLoaded = getUserDetails();
}
getUserDetails() async {
final String url = 'https://yallservice.com/api/v1/departments';
final response = await http.get(url);
final responseJson = json.decode(response.body);
var data = responseJson['data'];
setState(() {
for (Map user in data) {
_allResults.add(ItemModel.fromJson(user));
}
});
searchResultsList();
return "complete";
}
_onSearchChanged() {
searchResultsList();
}
searchResultsList() {
List<ItemModel> showResults = [];
if (_searchController.text != "") {
for (var tripSnapshot in _allResults) {
String title = tripSnapshot.about;
print(title + title);
if (title.contains(_searchController.text)) {
showResults.add(tripSnapshot);
}
}
} else {
showResults = List.from(_allResults);
}
setState(() {
_resultsList = showResults;
});
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: BackButton(),
title: Container(
color: Colors.white,
child: TextField(
controller: _searchController,
decoration: InputDecoration(prefixIcon: Icon(Icons.search)),
),
),
),
body: Container(
color: Colors.grey.shade300,
child: Column(
children: <Widget>[
Expanded(
child: ListView.builder(
itemCount: _resultsList.length,
itemBuilder: (BuildContext context, int index) {
return Container(
color: Colors.white,
child: ListTile(
subtitle: Text(_resultsList[index].about),
));
// return Card(
// index: index,
// data: _resultsList,
// );
},
)),
],
),
),
);
}
}

This is due to the encoding of white spaces in RTL strings.
Try to trim the TextField text before you search for it.
Special trim method
String trim(String string) {
assert(string != null);
final stringList = string.characters.toList();
final whitespaces = ['8206', '8207', '32'];
while (whitespaces.contains(stringList.last.runes.join()))
stringList.removeLast();
while (whitespaces.contains(stringList.first.runes.join()))
stringList.remove(stringList.first);
return stringList.join();
}
Updated searchResultsList
searchResultsList() {
List<ItemModel> showResults = [];
if (_searchController.text != "") {
for (var tripSnapshot in _allResults) {
String title = tripSnapshot.about;
if (title.contains(trim(_searchController.text))) {
showResults.add(tripSnapshot);
}
}
} else {
showResults = List.from(_allResults);
}
setState(() {
_resultsList = showResults;
});
}
Ref: Text fields' values do not get trimmed correctly when textDirection: TextDirection.rtl #68093
Improvement
Your search is currently case-sensitive. Maybe you should make it case-insensitive?
searchResultsList() {
setState(() {
_resultsList = _searchController.text.isNotEmpty
? _allResults
.where((tripSnapshot) => tripSnapshot.about
.toLowerCase()
.contains(trim(_searchController.text).toLowerCase()))
.toList()
: List.from(_allResults);
});
}

I fixed the problem just by putting textDirection: TextDirection.rtl, to my TextField

Related

the flutter audio wiveforms package does not display waveforms

I hope you are well, I have a big problem with the flutter audio waveforms package, indeed I want to display the waveforms of my voice files in a folder, but they are not displayed and when I display the value of playerController.bufferData I get a null, please how can I manage this problem, I have already spent days on it.
Sincerely
below are my classes
import 'dart:async';
import 'dart:io';
import 'package:audio_recorder/AudioWaveFormsWidget.dart';
import 'package:audio_waveforms/audio_waveforms.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:record/record.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Audio Recorder',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Audio Recorder'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
//late final PlayerController playerController1;
final record = Record();
int _recordDuration = 0;
Timer? _timer;
RecordState _recordState = RecordState.stop;
StreamSubscription<RecordState>? _recordSub;
final List<File> _audioFile = [];
#override
void initState() {
super.initState();
//Listening record state
_recordSub = record.onStateChanged().listen((recordState) {
setState(() => _recordState = recordState);
});
initCheckPermission();
setState(() {
initFileInDir();
});
}
#override
void dispose() {
_timer?.cancel();
_recordSub?.cancel();
record.dispose();
super.dispose();
}
Future initCheckPermission() async {
final statusMicrophone = await Permission.microphone.request();
final statusStorage = await Permission.storage.request();
if (statusMicrophone != PermissionStatus.granted ||
statusStorage != PermissionStatus.granted) {
await Permission.microphone.request();
await Permission.storage.request();
}
}
void _startTimer() {
_timer?.cancel();
_timer = Timer.periodic(const Duration(seconds: 1), (Timer t) {
setState(() => _recordDuration++);
});
}
Widget _buildText() {
if (_recordState != RecordState.stop) {
return _buildTimer();
}
return const Text("Waiting to record");
}
String _formatNumber(int number) {
String numberStr = number.toString();
if (number < 10) {
numberStr = '0$numberStr';
}
return numberStr;
}
Widget _buildTimer() {
final String minutes = _formatNumber(_recordDuration ~/ 60);
final String seconds = _formatNumber(_recordDuration % 60);
return Text(
'$minutes : $seconds',
style: const TextStyle(color: Colors.red),
);
}
Future<Directory> _getDir() async {
//Check platform and adjust settings
final tempDir = Platform.isAndroid
? await getExternalStorageDirectory()
: await getApplicationDocumentsDirectory();
Directory finalPath;
if (Platform.isAndroid) {
String buildDir =
tempDir!.path.replaceFirst("/data/", "/media/").split("files").first;
buildDir += "AudioRecorder"; // Plus ajout du nom de l'application
return finalPath = await Directory(buildDir).create(recursive: true);
} else {
return finalPath = await Directory(tempDir!.path).create(recursive: true);
}
}
void initFileInDir() async {
Directory finalPath = await _getDir();
var exists = await finalPath.exists();
if (exists) {
finalPath.list(recursive: false).forEach((element) {
File file = File(element.path);
_audioFile.add(file);
});
}
}
Widget _buildStopAndPlayIcon() {
if (_recordState != RecordState.stop) {
return const Icon(Icons.stop);
} else {
return const Icon(Icons.mic);
}
}
Future<void> _start() async {
Directory finalPath = await _getDir();
//Start recording
await record.start(
path: '${finalPath.path}/${DateTime.now().millisecondsSinceEpoch}.m4a',
encoder: AudioEncoder.aacLc, // by default
bitRate: 128000, // by default
samplingRate: 44100);
_recordDuration = 0;
_startTimer();
}
Future<File?> _stop() async {
_timer?.cancel();
_recordDuration = 0;
final path = await record.stop();
File? file;
if (path != null) {
file = File(path);
if (kDebugMode) {
print("--------------------------$path");
}
}
return file;
}
Future<void> _pause() async {
_timer?.cancel();
await record.pause();
}
Future<void> _resume() async {
_startTimer();
await record.resume();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Padding(
padding: const EdgeInsets.all(10.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: [
LimitedBox(
maxHeight: 650,
child: ListView.builder(
shrinkWrap: true,
itemCount: _audioFile.length,
itemBuilder: (context, index) {
var data = _audioFile[index];
return AudioWaveFormsWidget(path: data);
},
),
),
const Spacer(),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
_buildText(),
ElevatedButton(
onPressed: () async {
if (_recordState == RecordState.stop) {
_start();
} else {
File? newFile = await _stop();
setState((){ _audioFile.add(newFile!);});
}
},
style: ButtonStyle(
elevation: MaterialStateProperty.all(0),
shape: MaterialStateProperty.all(RoundedRectangleBorder(
borderRadius: BorderRadius.circular(100),
side: BorderSide.none))),
child: _buildStopAndPlayIcon(),
)
],
),
],
),
),
// This trailing comma makes auto-formatting nicer for build methods.
);
}
}
import 'dart:io';
import 'package:audio_waveforms/audio_waveforms.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
class AudioWaveFormsWidget extends StatefulWidget {
final File path;
//final PlayerController playerController1;
const AudioWaveFormsWidget({Key? key, required this.path}) : super(key: key);
#override
State<AudioWaveFormsWidget> createState() => _AudioWaveFormsWidgetState();
}
class _AudioWaveFormsWidgetState extends State<AudioWaveFormsWidget> {
late final PlayerController playerController1;
#override
void initState() {
playerController1 = PlayerController()
..addListener(() {
if (mounted) setState(() {});
});
_preparePlayer();
super.initState();
}
void _preparePlayer() async {
bool exist = await widget.path.exists();
if (exist) {
playerController1.preparePlayer(widget.path.path);
}
print("--------------------------------${playerController1.bufferData}");
}
void _playOrPausePlayer(PlayerController controller) async {
debugPrint(
'****************************************${controller.playerState.toString()}');
controller.playerState == PlayerState.playing
? await controller.pausePlayer()
: await controller.startPlayer(finishMode: FinishMode.pause);
}
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10.0),
shape: BoxShape.rectangle,
color: Colors.lightGreenAccent,
),
child: Row(
children: [
IconButton(
onPressed: () {
_playOrPausePlayer(playerController1);
},
icon: playerController1.playerState == PlayerState.playing
? const Icon(Icons.pause)
: const Icon(Icons.play_arrow)),
AudioFileWaveforms(
density: 1.0,
enableSeekGesture: true,
size: const Size(100.0, 70.0),
playerController: playerController1),
],
)),
);
}
}
if you're trying to record, try setting the bitRate to 48000 (worked for me on iOS when it wasn't showing the waveforms when recording).
final RecorderController recorderController = RecorderController()
..androidEncoder = AndroidEncoder.aac
..androidOutputFormat = AndroidOutputFormat.mpeg4
..iosEncoder = IosEncoder.kAudioFormatMPEG4AAC
..sampleRate = 44100
..bitRate = 48000;

Flutter Shared Preferences

Guys how to transfer data when I login.. For example when I login the transfer data are User ID, email and password.. So if I want to add something that requires the user id how do I call it?
This is my login method
void login() async {
if(passController.text.isNotEmpty && emailController.text.isNotEmpty) {
var response = await http.post(
Uri.parse("url"),
body: ({
'email': emailController.text,
'password': passController.text,
}));
if (response.statusCode == 200) {
final body = jsonDecode(response.body);
print(body.toString());
List<dynamic> data = body["Details"];
print(data[0]['email']);
pageRoute(data[0]['name']);
} else {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text("Wrong password")));
}
} else {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text("Sila isi tempat kosong")));
}
}
void pageRoute(data) async {
//STORE VALUE IN SHARED PREFERENCES
SharedPreferences pref = await SharedPreferences.getInstance();
await pref.setString("login", data);
Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(builder: (context) => nav()),
(route) => false);
This is where I want to take the user id without put it on the textfield.
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:http/http.dart' as http;
import '../Utils/lib.dart';
class CarList extends StatefulWidget {
const CarList({Key? key}) : super(key: key);
#override
State<CarList> createState() => _CarListState();
}
class _CarListState extends State<CarList> {
var userController = TextEditingController();
// late SharedPreferences logindata;
// String? Email;
final pref = Pref();
// late String name;
// late String registeration_no;
#override
void initState() {
// TODO: implement initState
super.initState();
initial();
}
void initial() async {
if (pref.isLogin()) {
final body = jsonDecode(pref.getLogin());
print(body['Details']['user_id'].toString());
}
return null;
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: ListView(
children: <Widget>[
Container(
padding: const EdgeInsets.all(10),
child: TextField(
controller: userController,
decoration: const InputDecoration(
border: OutlineInputBorder(),
suffixIcon: Icon(Icons.email),
labelText: 'User ID',
),
),
),
Container(
margin: EdgeInsets.all(25),
child: TextButton(
child: Text('test',
style: TextStyle(fontSize: 20.0,
color: Colors.blueAccent,
backgroundColor: Colors.white),
),
onPressed: () {
list();
},
),
)
]
)
);
}
void list() async {
{
var response = await http.post(
Uri.parse("url"),
body: ({
'user_id': userController.text,
}));
if (response.statusCode == 200) {
final body = jsonDecode(response.body);
// final SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
// sharedPreferences.setString('email', emailController.text);
pref.saveLogin(true, response.body);
print(body.toString());
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text("Successfully Login")));
}
}
}
}
Im kinda new with this flutter so might thankful with your help
You can do something like this:
This is store data in pageRoute.
void login() async {
if (passController.text.isNotEmpty && emailController.text.isNotEmpty) {
var response = await http.post(
Uri.parse("http://servisjer.me-tech.com.my/api/Login"),
body: ({
'email': emailController.text,
'password': passController.text,
}));
if (response.statusCode == 200) {
final body = jsonDecode(response.body);
print(body.toString());
List<dynamic> data = body["Details"];
print(data[0]['email']);
pageRoute(Data(data[0]['email'], data[0]['user_id']));
} else {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text("Wrong password")));
}
} else {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text("Sila isi tempat kosong")));
}
}
void pageRoute(Data data) async {
MySharedPreferences().storeUser(data);
Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(builder: (context) => nav()), (route) => false);
}
MySharedPreferences
class MySharedPreferences {
Future<void> storeUser(Data data) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString("email", data.email);
prefs.setInt("user_id", data.userId);
}
Future getUserId() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
var userId = prefs.getInt("user_id");
return userId;
}
}
In CarList, retrieve data using this way
#override
void initState() {
MySharedPreferences().getUserId().then((value) {
setState(() {
userController.text = value.toString();
});
});
//TODO: IMPLEMENT INITSTATE
super.initState();
}
Data
class Data {
var email;
var userId;
Data(this.email,this.userId);
}

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.

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

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;
}

Categories

Resources