I have problem with read my own custom API. When I try to read it a have an error :
" NoSuchMethodError: The method'[]' was called on null.
Receiver: null
Tried calling : "
My DataSource :
class MotivationQuotesRemoteDioDataSources {
Future<List<Map<String, dynamic>>?> getQuotesRespondeData() async {
final response = await Dio().get<List<dynamic>>(
'https://my-json-server.typicode.com/jargawl/json/quotes');
final listDynamic = response.data;
if (listDynamic == null) {
return null;
}
return listDynamic.map((e) => e as Map<String, dynamic>).toList();
}
}
My Repositories :
class MotivationQuotesRepositories {
MotivationQuotesRepositories(
{required this.motivationQuotesRemoteDioDataSources});
final MotivationQuotesRemoteDioDataSources
motivationQuotesRemoteDioDataSources;
Future<List<QuotesModel>> getQuotesModel() async {
final json =
await motivationQuotesRemoteDioDataSources.getQuotesRespondeData();
if (json == null) {
return [];
}
return json.map((item) => QuotesModel.fromJson(item)).toList();
}
}
My model:
class QuotesModel {
QuotesModel(
this.text,
this.author,
);
final String text;
final String author;
QuotesModel.fromJson(Map<String, dynamic> json)
: text = json['quotes']['text'],
author = json['quotes']['author'];
}
I try to use there :
class QoutesCardList extends StatelessWidget {
const QoutesCardList({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return SliverToBoxAdapter(
child: BlocProvider(
create: (context) => QoutesCardCubit(
motivationQuotesRepositories: MotivationQuotesRepositories(
motivationQuotesRemoteDioDataSources:
MotivationQuotesRemoteDioDataSources(),
),
)..start(),
child: BlocBuilder<QoutesCardCubit, QoutesCardState>(
builder: (context, state) {
switch (state.status) {
case Status.initial:
return const Center(
child: Text('Initial state'),
);
case Status.loading:
return const Center(
child: CircularProgressIndicator(),
);
case Status.success:
return ListView(
scrollDirection: Axis.horizontal,
children: [
for (final quotesModel in state.results)
QoutesCard(quotesModel: quotesModel)
],
);
case Status.error:
return Center(
child: Text(state.errorMessage ?? 'Unknown error'),
);
}
},
),
),
);
}
}
Can someone tell me why it don't work ? It should be a simple ListView (with Containers) with same motivation quotes.
There are no 'quotes' in data:
[
{
text: "Genius is one percent inspiration and ninety-nine percent perspiration.",
author: "Thomas Edison"
},
...
]
So the model should look like this:
class QuotesModel {
QuotesModel(
this.text,
this.author,
);
final String text;
final String author;
QuotesModel.fromJson(Map<String, dynamic> json):
text = json['text'],
author = json['author'];
}
Here response is a string. Json decode it to map it
final listDynamic = json.decode(response.data);
Plus dont define the type here
final response = await Dio().get(
'https://my-json-server.typicode.com/jargawl/json/quotes');
Related
I don't know where this error is coming from
enter image description here
the debug console says the error is in the returning line and the return line return just returning a widget but the error is about string is null i don't from where this error is coming
this is notes_view.dart file
class NotesView extends StatefulWidget {
const NotesView({super.key});
#override
State<NotesView> createState() => _NotesViewState();
}
class _NotesViewState extends State<NotesView> {
late final FirebaseCloudStorage _notesService;
String get userId => AuthService.firebase().currentUser!.id;
#override
void initState() {
_notesService = FirebaseCloudStorage();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.blue[100],
appBar: AppBar(
title: const Text("Your Notes"),
actions: [
IconButton(
onPressed: () {
Navigator.of(context).pushNamed(createOrUpdateNoteRoute);
},
icon: const Icon(Icons.add),
),
PopupMenuButton<MenuActions>(
onSelected: (value) async {
switch (value) {
case MenuActions.logout:
final shouldLogout = await showLogoutDialog(context);
if (shouldLogout) {
await AuthService.firebase().logOut();
Navigator.of(context)
.pushNamedAndRemoveUntil(loginRoute, (_) => false);
}
break;
}
},
itemBuilder: (context) {
return const [
PopupMenuItem<MenuActions>(
value: MenuActions.logout, child: Text("Log out")),
];
},
)
],
),
body: StreamBuilder(
stream: _notesService.allNotes(ownerUserId: userId),
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
case ConnectionState.active:
if (snapshot.hasData) {
final allNotes = snapshot.data as Iterable<CloudNote>;
return NotesListView(
notes: allNotes,
onDeleteNote: (note) async {
await _notesService.deleteNote(
documentId: note.documentId);
print(note.documentId);
},
onTap: (note) {
Navigator.of(context).pushNamed(
createOrUpdateNoteRoute,
arguments: note,
);
},
);
} else {
return const CircularProgressIndicator();
}
default:
return const CircularProgressIndicator();
}
},
));
}
}
this is notes_list_view.dart file
typedef NoteCallback = void Function(CloudNote note);
class NotesListView extends StatelessWidget {
final Iterable<CloudNote> notes;
final NoteCallback onDeleteNote;
final NoteCallback onTap;
const NotesListView({
Key? key,
required this.notes,
required this.onDeleteNote,
required this.onTap,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: notes.length,
itemBuilder: (context, index) {
final note = notes.elementAt(index);
return ListTile(
onTap: () {
onTap(note);
},
textColor: Colors.black87,
title: Text(
note.text,
maxLines: 1,
softWrap: true,
overflow: TextOverflow.ellipsis,
),
trailing: IconButton(
icon: Icon(
Icons.delete,
color: Colors.red[200],
),
onPressed: () async {
final shouldDelete = await deleteDialog(context);
if (shouldDelete) {
onDeleteNote(note);
}
},
),
);
},
);
}
}
this is the firebase_cloud_storage.dart file
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:mynotes/services/cloud/cloud_note.dart';
import 'package:mynotes/services/cloud/cloud_storage_constants.dart';
import 'package:mynotes/services/cloud/cloud_storage_exceptions.dart';
class FirebaseCloudStorage {
final notes = FirebaseFirestore.instance.collection('notes');
Future<void> deleteNote({required String documentId}) async {
try {
await notes.doc(documentId).delete();
} catch (e) {
throw CouldNotDeleteNoteException();
}
}
Future<void> updateNote({
required String documentId,
required String text,
}) async {
try {
await notes.doc(documentId).update({textFieldName: text});
} catch (_) {
throw CouldNotUpdateNotesException();
}
}
Stream<Iterable<CloudNote>> allNotes({required String ownerUserId}) {
return notes.snapshots().map((event) => event.docs
.map((doc) => CloudNote.fromSnapshot(doc))
.where((note) => note.ownerUserId == ownerUserId));
}
Future<Iterable<CloudNote>> getNotes({required String ownerUserId}) async {
try {
return await notes
.where(ownerUserIdFieldName, isEqualTo: ownerUserId)
.get()
.then(
(value) => value.docs.map((doc) => CloudNote.fromSnapshot(doc)),
);
} catch (e) {
throw CouldNotGetAllNotesException();
}
}
Future<CloudNote> createNewNote({required String ownerUserId}) async {
final document = await notes.add({
ownerUserIdFieldName: ownerUserId,
textFieldName: '',
});
final fetchedNote = await document.get();
return CloudNote(
documentId: fetchedNote.id,
ownerUserId: ownerUserId,
text: '',
);
}
static final FirebaseCloudStorage _shared =
FirebaseCloudStorage._sharedInstance();
FirebaseCloudStorage._sharedInstance();
factory FirebaseCloudStorage() => _shared;
}
#immutable
class CloudNote {
final String documentId;
final String ownerUserId;
final String text;
const CloudNote({
required this.documentId,
required this.ownerUserId,
required this.text,
});
CloudNote.fromSnapshot(QueryDocumentSnapshot<Map<String, dynamic>> snapshot)
: documentId = snapshot.id,
ownerUserId = snapshot.data()[ownerUserIdFieldName],
text = snapshot.data()[textFieldName] as String;
}
I will like to accept null data while reading map, try
text = snapshot.data()[textFieldName] ?? "got null value";
CloudNote.fromSnapshot(QueryDocumentSnapshot<Map<String, dynamic>> snapshot)
: documentId = snapshot.id,
ownerUserId = snapshot.data()[ownerUserIdFieldName] ?? "default value",
text = snapshot.data()[textFieldName] ?? "Default value";
class Organization_Api{
static Future<List<dynamic>> getData(
{required String target, String? limit}) async {
try {
var uri = Uri.https(
BASE_URL,
"api/$target",
target == "organizations"
? {
"offset": "0",
"limit": limit,
}
: {});
var response = await http.get(uri);
var data = jsonDecode(response.body);
List tempList = [];
if (response.statusCode != 200) {
throw data["message"];
}
for (var v in data) {
tempList.add(v);
}
return tempList;
} catch (error) {
log("An error occured $error");
throw error.toString();
}
}
static Future<List<Organization>> getAllOrganizations(
{required String limit}) async {
List temp = await getData(
target: "organizations",
limit: limit,
);
return Organization.organizationsToList(temp);
}
static Future<Organization> getOrganizationById({required String id}) async {
try {
var uri = Uri.https(
BASE_URL,
"api/organizations/$id",
);
var response = await http.get(uri);
var data = jsonDecode(response.body);
if (response.statusCode != 200) {
throw data["message"];
}
return Organization.fromJson(data);
} catch (error) {
log("an error occured while getting organization info $error");
throw error.toString();
}
}
}
class HomeScreen extends StatefulWidget {
const HomeScreen({Key? key}) : super(key: key);
static String routeName = "/home";
#override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
Future<List<Organization>>? result ;
void initState(){
result = Organization_Api.getAllOrganizations(limit: '4');
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Organizations", style: TextStyle(color: Colors.black),
),
backgroundColor: Colors.white,
centerTitle: true,
),
body: Padding(
padding: EdgeInsets.all(10.0),
child: Column(
children:
<Widget>[
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children:<Widget>[
ListView(
shrinkWrap: true,
children:<Widget> [result],
)
],
),
)
],
),
),
);
}
}
class Organization{
final int OrganizationId;
final String OrganizationName;
Organization({required this.OrganizationId,required this.OrganizationName});
factory Organization.fromJson(Map<String,dynamic> json){
return Organization(OrganizationId: json['OrganizationId'], OrganizationName: json['OrganizationName']);
}
Map toJson(){
return{
"OrganizationId": this.OrganizationId,
"OrganizationName": this.OrganizationName,
};
}
static List<Organization> organizationsToList(List organizationToList) {
return organizationToList.map((data) {
return Organization.fromJson(data);
}).toList();
}
}
Error = The element type >'Future<List>?' can't be assigned to the list type 'Widget'.
I just want to check the data coming from the service, but I couldn't find how to do it.
What did I do wrong or what did I miss to list the incoming data?
I shared the screen page and the codes on how I got the information from the service.
Your Organization_Api.getAllOrganizations provide a future. You can use FutureBuilder.
class _HomeScreenState extends State<HomeScreen> {
Future<List<Organization>>? myFuture;
#override
void initState() {
myFuture = Organization_Api.getAllOrganizations(limit: '4');
super.initState();
}
And on future builder
FutureBuilder<List<Organization>?>(
future: myFuture,
builder: (context, snapshot) {
if (snapshot.hasData && snapshot.data!.isNotEmpty) {
return ListView(
shrinkWrap: true,
//children: snapshot.data!, // when `Organization` is a widget
children:// when `Organization` is a data model class
snapshot.data!.map((e) => Text(e.toString())).toList(),
);
}
return CircularProgressIndicator();
},
)
Also check Randal L. Schwartz video on using Future
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}';
}
Hello guys I face this problem when I Create a Search Delegate in a flutter
I try to call data from Firebase and add it in List Class but it shows me this error
List<dynamic> is not a subtype fo type List<Itemshop> of function result
Problem Here
List<ItemShop> ItemShopList = [];
CollectionReference ItemShopRef =
FirebaseFirestore.instance.collection('ItemShop');
List filterItemShop = [];
int counter = 0;
Future getData() async {
var responsce = await ItemShopRef.get();
responsce.docs.forEach((element) {
ItemShop itemShop = ItemShop(element["ItemCatgore"], element["ItemImage"],
element["ItemKG"], element['ItemName'], element["ItemPrice"]);
if (counter == 0) {
ItemShopList.add(itemShop);
}
});
print(ItemShopList);
return ItemShopList;
}
Class for ItemShop
class ItemShop {
final String ItemCatgore, ItemImage, ItemKG, ItemName;
int ItemPrice;
ItemShop(this.ItemCatgore, this.ItemImage, this.ItemKG, this.ItemName,
this.ItemPrice);
}
Full Code:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
class SearchPage extends StatefulWidget {
const SearchPage({Key? key}) : super(key: key);
#override
State<SearchPage> createState() => _SearchPageState();
}
class _SearchPageState extends State<SearchPage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Color.fromARGB(255, 184, 132, 132),
actions: [
IconButton(
onPressed: () {
showSearch(context: context, delegate: mySearch());
},
icon: Icon(Icons.search))
],
),
);
}
}
class mySearch extends SearchDelegate {
List<ItemShop> ItemShopList = [];
CollectionReference ItemShopRef =
FirebaseFirestore.instance.collection('ItemShop');
List filterItemShop = [];
int counter = 0;
Future getData() async {
var responsce = await ItemShopRef.get();
responsce.docs.forEach((element) {
ItemShop itemShop = ItemShop(element["ItemCatgore"], element["ItemImage"],
element["ItemKG"], element['ItemName'], element["ItemPrice"]);
if (counter == 0) {
ItemShopList.add(itemShop);
}
});
print(ItemShopList);
return ItemShopList;
}
////////////////////////////////////////////////
#override
List<Widget>? buildActions(BuildContext context) {
return [
IconButton(
onPressed: () {
query = "";
},
icon: Icon(Icons.close))
];
}
#override
Widget? buildLeading(BuildContext context) {
return IconButton(
onPressed: () {
close(context, null);
},
icon: Icon(Icons.arrow_back));
}
#override
Widget buildResults(BuildContext context) {
return FutureBuilder(
future: getData(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.data == null) {
return Center(
child: CircularProgressIndicator(),
);
} else {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int i) {
return snapshot.data[i].ItemName == query
? Card(
child: Column(
children: [
Container(
color: Colors.grey[200],
height: 150,
width: double.infinity,
child: Text(
snapshot.data[i].ItemName,
textAlign: TextAlign.center,
style: TextStyle(fontSize: 35),
),
),
Container(
child: Text(snapshot.data[i].ItemName),
)
],
),
)
: Container();
});
}
});
}
#override
Widget buildSuggestions(BuildContext context) {
filterItemShop = ItemShopList.where((element) =>
element.ItemName.toLowerCase().contains(query.toLowerCase())).toList();
return FutureBuilder(
future: getData(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.data == null) {
return Center(
child: CircularProgressIndicator(),
);
} else {
return ListView.builder(
itemCount:
query == "" ? snapshot.data.length : filterItemShop.length,
itemBuilder: (BuildContext context, int i) {
return InkWell(
onTap: () {
query = query == ""
? ItemShopList[i].ItemName
: filterItemShop[i].ItemName;
showResults(context);
},
child: Card(
child: query == ""
? ListTile(
leading: Text(snapshot.data[i].ItemName),
title: Text(snapshot.data[i].ItemName),
subtitle: Text(snapshot.data[i].ItemName),
)
: ListTile(
leading: Text(filterItemShop[i].ItemName),
title: Text(filterItemShop[i].ItemName),
subtitle: Text(filterItemShop[i].ItemName),
),
),
);
});
}
});
}
}
class ItemShop {
final String ItemCatgore, ItemImage, ItemKG, ItemName;
int ItemPrice;
ItemShop(this.ItemCatgore, this.ItemImage, this.ItemKG, this.ItemName,
this.ItemPrice);
}
there, I think the better approach is not for each but map. and use type defines variable so you will not get type error as long as you do not use casting method. final List<Itemshop> x = responsce.docs.map((e)=>Itemshop.fromMap(e.data()..docId = e.id)).toList(); return x;
ypu can also just retun the map fucntion like return responsce.docs.map((e)=> ....
Itemshop should be ItemShop, standard dart format.
Itemshop.fromMap is a function that you build in Itemshop class. data classes always have this kind of helper. fromMap, toMap, fromJson, toJson. a lot of code generation in the dart for this if you don't want to write it yourself.
For example for your comment,
import 'dart:convert';
class ItemShop {
final String? itemCatgore;
final String? itemImage;
final String? ItemKG;
final String? ItemName;
final String? ItemPrice;
ItemShop({
this.itemCatgore,
this.itemImage,
this.ItemKG,
this.ItemName,
this.ItemPrice,
});
Map<String, dynamic> toMap() {
return {
'itemCatgore': itemCatgore,
'itemImage': itemImage,
'ItemKG': ItemKG,
'ItemName': ItemName,
'ItemPrice': ItemPrice,
};
}
factory ItemShop.fromMap(Map<String, dynamic> map) {
return ItemShop(
itemCatgore: map['itemCatgore'],
itemImage: map['itemImage'],
ItemKG: map['ItemKG'],
ItemName: map['ItemName'],
ItemPrice: map['ItemPrice'],
);
}
String toJson() => json.encode(toMap());
factory ItemShop.fromJson(String source) =>
ItemShop.fromMap(json.decode(source));
ItemShop copyWith({
String? itemCatgore,
String? itemImage,
String? ItemKG,
String? ItemName,
String? ItemPrice,
}) {
return ItemShop(
itemCatgore: itemCatgore ?? this.itemCatgore,
itemImage: itemImage ?? this.itemImage,
ItemKG: ItemKG ?? this.ItemKG,
ItemName: ItemName ?? this.ItemName,
ItemPrice: ItemPrice ?? this.ItemPrice,
);
}
#override
String toString() {
return 'ItemShop(itemCatgore: $itemCatgore, itemImage: $itemImage, ItemKG: $ItemKG, ItemName: $ItemName, ItemPrice: $ItemPrice)';
}
#override
bool operator ==(Object other) {
if (identical(this, other)) return true;
return other is ItemShop &&
other.itemCatgore == itemCatgore &&
other.itemImage == itemImage &&
other.ItemKG == ItemKG &&
other.ItemName == ItemName &&
other.ItemPrice == ItemPrice;
}
#override
int get hashCode {
return itemCatgore.hashCode ^
itemImage.hashCode ^
ItemKG.hashCode ^
ItemName.hashCode ^
ItemPrice.hashCode;
}
}
plus dart use camel case for all the variable and function (first latest is small later, second-word first letter is capital)
and all words first capital letter
Specify the type of future in futurebuilder, here it is list itemshop as shown below.
return FutureBuilder<List<ItemShop>>(
//TODO: YOUR CODE
);
#This is my model class
List<SliderModel> sliderModelFromJson(String str) => List<SliderModel>.from(json.decode(str).map((x) => SliderModel.fromJson(x)));
String sliderModelToJson(List<SliderModel> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class SliderModel {
SliderModel({
this.id,
this.title,
this.description,
this.image,
this.type,
this.url,
this.schoolid,
});
int id;
String title;
dynamic description;
String image;
String type;
String url;
String schoolid;
factory SliderModel.fromJson(Map<String, dynamic> json) => SliderModel(
id: json["id"],
title: json["title"],
description: json["description"],
image: json["image"],
type: json["type"],
url: json["url"],
schoolid: json["schoolid"],
);
Map<String, dynamic> toJson() => {
"id": id,
"title": title,
"description": description,
"image": image,
"type": type,
"url": url,
"schoolid": schoolid,
};
}
#this is my services class where i call my api
static Future<List<SliderModel>> getSliderData(String id) async{
var dio = don.Dio();
don.Response response =await dio.get("https://shikshyasoftware.com.np/CoreApplicationandAPIService-4617993073/api/shikshyanotice?schoolid=$id") ;
try{
var responseData = response.data;
if(response.statusCode==200){
print("responseData:-${responseData}");
return sliderModelFromJson(jsonEncode(responseData));
}
}catch(e){
rethrow;
}
}
#this is my controller class
class SliderController extends GetxController{
var isLoading = true.obs;
var sliderData = <SliderModel>[];
Future<void> fetchImageSilder(String id) async{
try{
isLoading(true);
var slider = await Services.getSliderData(id);
sliderData = slider;
print(sliderData.length);
}finally{
isLoading(false);
}
}
SliderModel findById(String id){
return sliderData.firstWhere((e) => e.schoolid == id,orElse: ()=>null);
}
}
#this is my view where i tried to call the controller and load the image like this
var isInit = true;
void didChangeDependencies() {
// TODO: implement didChangeDependencies
if(isInit) {
final schoolId = ModalRoute.of(context).settings.arguments;
Get.put(SliderController().fetchImageSilder(schoolId));
}
isInit = false;
super.didChangeDependencies();
}
SliderController sliderData = Get.put(SliderController());
Obx((){
if(sliderData.isLoading.value){
return Center(
child: LinearProgressIndicator(
minHeight: 95.h,
color: Colors.grey.shade100,
backgroundColor: Colors.grey.shade200,
),
);
}else{
return SizedBox(
// height: MediaQuery.of(context).size.height*0.15,
// width: MediaQuery.of(context).size.width*0.99,
height: 95.h,
width: double.infinity,
child:CarouselSlider(
items:sliderData.sliderData.map((e) =>ClipRRect(
borderRadius: BorderRadius.circular(5.r),
child: Stack(
fit: StackFit.expand,
children: [
Image.network(e.image??Image.asset("icons/shik_banner_20200553123753.png"),fit: BoxFit.fill,errorBuilder: (BuildContext context, Object exception, StackTrace stackTrace) {
return Image.asset("icons/shik_banner_20200553123753.png");
},)
],
),
) ).toList()
, options: CarouselOptions(viewportFraction: 1,autoPlay: false,autoPlayAnimationDuration: const Duration(milliseconds: 800),
),
),
);
}
#i am not getting any error but my loading screen continues to load and image is not shown and i am getting show this W/Choreographer(22264): Frame time is 16.052103 ms in the future! Check that graphics HAL is generating vsync timestamps using the correct timebase. in my run and i dont know what to do to load my image need your help thanks in advance
Try to use folllowing code. I will suggest to use the StatefulWidget Widget to call your methods specially if your methods having the paramters. initState helps to call our functions. If you finds this answer helpful please upvote
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> {
final _sliderController= Get.put(SliderController());
#override
void initState() {
super.initState();
_sliderController.fetchImageSilder(schoolId);//Here you can pass parameters to your function
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Obx((){
if(sliderData.isLoading.value){
return Center(
child: LinearProgressIndicator(
minHeight: 95.h,
color: Colors.grey.shade100,
backgroundColor: Colors.grey.shade200,
),
);
}else{
return Widget()// Pass your Widget
}
);
}
}
// Getx Controller
class SliderController extends GetxController{
var isLoading = true.obs;
RxList<SliderModel> sliderData = [].obs; // If you are using `Obx()` then your list type should be obs
Future<void> fetchImageSilder(String id) async{
try{
isLoading(true);
var slider = await Services.getSliderData(id);
sliderData.add(slider); // Add your data into `RxList`
print(sliderData.length);
}finally{
isLoading(false);
}
}
SliderModel findById(String id){
return sliderData.firstWhere((e) => e.schoolid == id,orElse: ()=>null);
}
}