Reputation:
I'm fresher in Flutter. it's my First time to implement API calls in Dart. I need to write API calls using callbacks. I don't have a programming background so please help me how to write that. I added a link below I need to list the title and add a click Listener. please help me.
base url: enter link description here
Upvotes: 1
Views: 3664
Reputation: 1543
You can use futurebuilder to call an api. Here I have gave full demonstration how to call api with loader and update view.
dependencies:
flutter:
sdk: flutter
http: "^0.12.0"
after adding dependency import it
import 'package:http/http.dart' as http;
class Home extends StatelessWidget {
@override
Widget build(BuildContext context) {
// TODO: implement build
return Scaffold(
body: ListView(
children:[
updateTopratedMovie(context),
]
),
);
}
Future<dynamic> getTopratedMovie() async {
String url =
'https://api.themoviedb.org/3/movie/top_rated';
http.Response response = await http.get(url);
return json.decode(response.body);
}
Widget updateTopratedMovie(context) {
return FutureBuilder(
future: getTopratedMovie(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasData) {
if (snapshot.data != null) {
dynamic content = snapshot.data;
return SizedBox(
height: 500.0,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 0.0),
child: Container(
// elevation: 2.0,
child: ListView.builder(
// scrollDirection: Axis.horizontal,
itemCount: content['results'].length,
itemBuilder: (context, i) =>
Container(
height:100.0,
color:Colors.red
child:Text(i);
),
),
),
);
}
} else {
return Container(
height: 120.0,
width: MediaQuery.of(context).size.width,
child: Center(
child: CircularProgressIndicator(
backgroundColor: Color(0xff00d2ff),
),
),
);
}
},
);
}
}
Upvotes: 1
Reputation: 6044
In your pubspec.yaml
file add the following:
dependencies:
flutter:
sdk: flutter
http: 0.12.0+1
In your code:
import 'package:http/http.dart' as http;
const String url = 'https://www.redzoc.com/api/youtube/show/v2/get_trending.php?limit=50&offset=0';
final http.Request request = http.Request('GET', Uri.parse(url));
final http.StreamedResponse response = await http.Client().send(request);
final int statusCode = response.statusCode;
final String responseData =
await response.stream.transform(utf8.decoder).join();
if(statusCode == 200) {
print(responseData);
} else {
print('error: code $statusCode');
}
Upvotes: 1
Reputation: 673
void fetchData() async {
final response =
await get('https://www.redzoc.com/api/youtube/show/v2/get_trending.php?limit=50&offset=0');
final imageModel = YourModelClass.fromJson(json.decode(response.body));
}
Upvotes: 0