[Flutter] #3 http interface

     

follow the flutter.dev homepage tutorial guide.

  • I think, it's the best way to learn flutter that learn from flutter.dev website.
  • This article is based on flutter.dev

use the http package on flutter

  • Let's use rest api protocol on flutter.

    1. First, we need to add http package.
    2. Seconde, import package on source. import 'package:http/http.dart' as http. as http is optional.
    3. Third, add android.permission.INTERNET for android. <uses-permission android:name="android.permission.INTERNET" /> in AndroidManifest.xml.
  • You can download http package write the command flutter pub add http.

Make a api request

  • Write this sample source.
Future<http.Response> fetchAlbum() {
  return http.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'));
}
  • I try it on other source, not main.dart. Maybe flutter framework have a design patten make a folder and sources, but I don'k know right now. In react, I wrote the api codes in api.js. I try it again.

Make a model class

  • I don't know whether it called model or not in flutter, I use the word model express the class.
  • The sample api url ~/ablums/1 has 3 field userId, id, title. So we need to make a class has 3 value.
class Album {
  final int userId;
  final int id;
  final String title;

  Album({
    required this.userId,
    required this.id,
    required this.title,
  });

  factory Album.fromJson(Map<String, dynamic> json) {
    return Album(
      userId: json['userId'],
      id: json['id'],
      title: json['title'],
    );
  }
}
  • I wrote this code model.dart. It's my way lol.

Change a api request class

Future<Album> fetchAlbum() async {
  final response = await http
      .get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'));

  if (response.statusCode == 200) {
    // If the server did return a 200 OK response,
    // then parse the JSON.
    return Album.fromJson(jsonDecode(response.body));
  } else {
    // If the server did not return a 200 OK response,
    // then throw an exception.
    throw Exception('Failed to load album');
  }
}
  • We need to change the code fetchAlbum to return Album class from return http.response class.

Test it

class ApiTestWidget extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
    return _ApiTestWidgetState();
  }
}

class _ApiTestWidgetState extends State<ApiTestWidget>{
  late Future<Album> futureAlbum;
  @override
  void initState(){
    super.initState();
    futureAlbum = fetchAlbum();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: FutureBuilder<Album>(
        future: futureAlbum,
        builder: (context, snapshot){
          if(snapshot.hasData){
            return Container(
              padding: EdgeInsets.all(24),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(snapshot.data!.id.toString()),
                  Text(snapshot.data!.userId.toString()),
                  Text(snapshot.data!.title.toString()),
                ],
              ),

            );
              Text(snapshot.data!.title);
          }else if(snapshot.hasError){
            return Text('${snapshot.error}');
          }
          return const CircularProgressIndicator();
        },
      ),
    );
  }

}
  • This widget is show response of api call. The core function fetchAlbum() is in initState(). It runs one time when the app run.
  • They don't recommand calling in build(). Because, It runs often.

Update data over api call

  • Last post (#2 stateful widget) we made a widget has a state. When I tapped the container, the state value changes. How does it make with api call.
  • This is based on fultter.dev
          ElevatedButton(onPressed: (){
            setState(() {
              futureAlbum = fetchAlbum2();
            });
          }, child: const Text('change')),
  • It's simple than I think. Just add the code setState anywhere in widget.
반응형

댓글

Designed by JB FACTORY