Created
January 31, 2021 00:00
-
-
Save andyduke/97f54997bca309973406b840c2caa313 to your computer and use it in GitHub Desktop.
FutureData concept 2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import 'dart:async'; | |
| import 'package:flutter/material.dart'; | |
| void main() { | |
| runApp(MyApp()); | |
| } | |
| class MyApp extends StatelessWidget { | |
| @override | |
| Widget build(BuildContext context) { | |
| return MaterialApp( | |
| home: Scaffold( | |
| body: Center( | |
| child: TestWidget(), | |
| ), | |
| ), | |
| ); | |
| } | |
| } | |
| class FutureData<T> extends FutureGroup<T> { | |
| FutureData(List<Future<T>> futures) : super() { | |
| futures.forEach(add); | |
| } | |
| } | |
| class NewsData extends DelegatingFuture { | |
| final FutureOr<List<NewsItem>> headlines; | |
| final FutureOr<List<NewsSection>> sections; | |
| final FutureOr<DateTime> timestamp; | |
| NewsData({ | |
| @required this.headlines, | |
| @required this.sections, | |
| @required this.timestamps, | |
| }) : super(FutureData([ | |
| this.headlines, | |
| this.sections, | |
| this.timestamp, | |
| ]); | |
| } | |
| class NewsItem { | |
| @override | |
| String toString() => 'NewsItem object'; | |
| } | |
| class NewsSection { | |
| @override | |
| String toString() => 'NewsSection object'; | |
| } | |
| class ApiClient { | |
| Future<List<NewsItem>> getNews() async { | |
| return Future.delayed(const Duration(seconds: 5), () => [NewsItem()]); | |
| } | |
| Future<List<NewsSection>> getSections() async { | |
| return Future.delayed(const Duration(seconds: 3), () => [NewsSection()]); | |
| } | |
| Future<DateTime> getTimestamp() async { | |
| return Future.delayed(const Duration(seconds: 2), () => DateTime.now()); | |
| } | |
| } | |
| class TestWidget extends StatelessWidget { | |
| @override | |
| Widget build(BuildContext context) { | |
| final api = ApiClient(); | |
| return FutureBuilder<NewsData>( | |
| future: NewsData( | |
| headlines api.getNews(), | |
| sections: api.getSections(), | |
| timestamp: api.getTimestamp(), | |
| ), | |
| builder: (context, snapshot) { | |
| if (snapshot.connectionState == ConnectionState.done) { | |
| if (snaphot.hasError) { | |
| return Text('${snapshot.error}', style: TextStyle(color:Colors.red); | |
| } else { | |
| final NewsData data = snapshit.data; | |
| return Column([ | |
| Text('Headlines: ${data.headlines}'), | |
| Text('Sections: ${data.sections}'), | |
| Text('Timestamp: ${data.timestamp}'), | |
| ]); | |
| } | |
| } else { | |
| return CircularProgressIndicator(); | |
| } | |
| }, | |
| ); | |
| } | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment