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.
CodePudding user response:
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');
CodePudding user response:
There are no 'quotes' in data, 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'];
}