how can I solve this problem. I know there are a lot of answers about this problem in internet. But I could not adapt them. My code for get values from WordPress website with WordPress own API.
file 1 main.dart
import 'dart:html';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'wp-api.dart';
void main() {
runApp(benimApp());
}
class benimApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return GetMaterialApp(
theme: ThemeData(),
debugShowCheckedModeBanner: false,
home: Scaffold(
body: SafeArea(
child: Column(children: [
xMyHomePage(),
]),
),
),
);
}
}
class xMyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: FutureBuilder(
future: fetchWpPosts(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.builder(
itemCount: 4,
itemBuilder: (BuildContext context, int index) {
Map wppost = snapshot.data[index];
// return Text(wppost['title']['rendered']);
},
);
}
return CircularProgressIndicator();
}),
),
);
}
}
file 2 wp-api.dart
import 'package:http/http.dart' as http;
import 'dart:convert';
Future<List> fetchWpPosts() async {
final response = await http.get(
Uri.parse('https://www.yazilimaktif.com/wp-json/wp/v2/posts?_embed'));
var convertDataJson = jsonDecode(response.body);
return convertDataJson;
}
I am getting error like this title
CodePudding user response:
Have you try with a return type of Future<List<dynamic>>
, like this:
Future<List<dynamic>> fetchWpPosts() async {
try {
final response = await http.get(
Uri.parse('https://www.yazilimaktif.com/wp-json/wp/v2/posts?_embed'));
if (response.statusCode == 200) {
var convertDataJson = jsonDecode(response.body);
return convertDataJson;
} else {
return [];
}
}
catch (error) {
return [];
}
}
And add default value in case of errors to be shure don't returning null value.
CodePudding user response:
The problem is that data returned from snapshot is optional. So you need to unwrap it or check for null.
Your code will look like this:
FutureBuilder(
future: fetchWpPosts(),
builder: (context, snapshot) {
if (snapshot.hasData) {
List<dynamic> returnedList = snapshot.data! as List;
return ListView.builder(
itemCount: 4,
itemBuilder: (BuildContext context, int index) {
Map wppost = returnedList[index];
return Text(wppost['title']['rendered']);
},
);
}
return CircularProgressIndicator();
}),