Show menu

main.dart

  void main() => runApp(DemoApp());

  class DemoApp extends StatelessWidget {
    final req = const RequestItem(
      url:  "https://jsonplaceholder.typicode.com/posts/10"
    );

    const DemoApp();

    @override
    Widget build(BuildContext context) {
      return MaterialApp(
        home: Scaffold(
          appBar: AppBar(
            title: const Text("Request Demo"),
          ),
          body: Center(
            child: HTTPWidget(req),
          )
        )
      );
    }

  }
  

item.dart

  class Item {
    final int id;
    final String title;
    Item({
      required this.id,
      required this.title
    });

    factory Item.fromJson(Map<String, dynamic> json) {
      return Item(
        id: json['id'] as int,
        title: json['title'] as String,
      );
    }
  }
  

base_request.dart

  abstract class HTTPRequest<T> {
    Future<T> execute();
  }
  

item_request.dart

  class RequestItem implements HTTPRequest<Item> {
    final String url;
    const RequestItem({ required this.url });

    Future<Item> execute() async {
      final response = await http.get(url);

      if (response.statusCode != 200) {
        throw http.ClientException("Oh darn!");
      }

      return _parseJson(response.body);
    }

    Item _parseJson(String response) =>
        Item.fromJson(jsonDecode(response));
  }
  

request_page.dart

  class HTTPWidget extends StatefulWidget {
    final HTTPRequest<Item> _request;
    const HTTPWidget(this._request);

    @override
    _HTTPWidgetState createState() => _HTTPWidgetState();
  }

  class _HTTPWidgetState extends State<HTTPWidget> {
    late final Future<Item> futureItems;

    @override
    void initState() {
      super.initState();
      futureItems = widget._request.execute();
    }

    @override
    Widget build(BuildContext context) {
      return FutureBuilder(
          future: futureItems,
          builder: (context, snapshot) {
            if (snapshot.hasError) {
              return const ErrorItemWidget();
            }

            if (snapshot.hasData) {
              return SuccessItemWidget(
                  snapshot.data
              );
            }

            return const Center(
                child: CircularProgressIndicator()
            );
          }
      );
    }
  }
  

success_widget.dart

  class SuccessItemWidget extends StatelessWidget {
    final Item? data;
    const SuccessItemWidget(this.data);

    @override
    Widget build(BuildContext context) {
      if (data != null) {
        return Text("${data!.id} - ${data!.title}");
      } else {
        return const Text("No data to show");
      }
    }
  }
  

error_widget.dart

  class ErrorItemWidget extends StatelessWidget {
    const ErrorItemWidget();

    @override
    Widget build(BuildContext context) {
      return const Icon(Icons.warning);
    }
  }
  

This website and the book are not official Google products. No affiliations are involved. Built with Java 14 and Vert.X

"Flutter and the related logo are trademarks of Google LLC. We are not endorsed by or affiliated with Google LLC"