Flutter make api call to load data via FutureBuilder
This is an example demonstrating how to use FutureBuilder to make an api call and load the data from the api response to a widget.
1. Install the http client library as this example will be using it. Run the following command within the project root folder to install it.
flutter pub add http
2. The async function that does the api call. All it does is to make an api call to get the ip address you are using.
FuturegetIPAddress() async { final url = Uri.parse('https://httpbin.org/ip'); final httpClient = HttpClient(); final request = await httpClient.getUrl(url); final response = await request.close(); final responseBody = await response.transform(utf8.decoder).join(); final String ip = jsonDecode(responseBody)['origin']; return ip; }
3. Create the widget via FutureBuilder. It calls the async function getIPAddress()
by passing in the function in the FutureBuilder’s future prop. The data is passed to the builder functions’s 2nd parameter. It passes the asyncSnapshotIpAddress to the widget that needs the data returned from the async function.
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 FutureBuilder( future: getIPAddress(), builder: (context, AsyncSnapshot ipAddress) { return MaterialApp( title: 'Flutter Future', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(title: 'Flutter Future Home Page', asyncSnapshotIpAddress: ipAddress), ); } ); } }
4. Using the data that is returned by the async function in a widget.
class MyHomePage extends StatefulWidget { final String title; final AsyncSnapshotasyncSnapshotIpAddress; const MyHomePage({ Key? key, required this.title, required this.asyncSnapshotIpAddress, }) : super(key: key); @override State createState() => _MyHomePageState(); } class _MyHomePageState extends State { String _ipAddress = ""; @override Widget build(context) { if (widget.asyncSnapshotIpAddress.hasData && widget.asyncSnapshotIpAddress.data != null) { _ipAddress = widget.asyncSnapshotIpAddress.data!; } return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( 'Your ip address is:', style: Theme.of(context).textTheme.headline5, ), Text( '$_ipAddress', style: Theme.of(context).textTheme.headline4, ), ], ), ), ); } }
All together
import 'dart:convert'; import 'dart:io'; import 'package:flutter/material.dart'; FuturegetIPAddress() async { final url = Uri.parse('https://httpbin.org/ip'); final httpClient = HttpClient(); final request = await httpClient.getUrl(url); final response = await request.close(); final responseBody = await response.transform(utf8.decoder).join(); final String ip = jsonDecode(responseBody)['origin']; return ip; } 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 FutureBuilder ( future: getIPAddress(), builder: (context, AsyncSnapshot ipAddress) { return MaterialApp( title: 'Flutter Future', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(title: 'Flutter Future Home Page', asyncSnapshotIpAddress: ipAddress), ); } ); } } class MyHomePage extends StatefulWidget { final String title; final AsyncSnapshot asyncSnapshotIpAddress; const MyHomePage({ Key? key, required this.title, required this.asyncSnapshotIpAddress, }) : super(key: key); @override State createState() => _MyHomePageState(); } class _MyHomePageState extends State { String _ipAddress = ""; @override Widget build(context) { if (widget.asyncSnapshotIpAddress.hasData && widget.asyncSnapshotIpAddress.data != null) { _ipAddress = widget.asyncSnapshotIpAddress.data!; } return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( 'Your ip address is:', style: Theme.of(context).textTheme.headline5, ), Text( '$_ipAddress', style: Theme.of(context).textTheme.headline4, ), ], ), ), ); } }
Search within Codexpedia
Search the entire web