My data isnt being refreshed when i try to refresh - flutter

When i refresh the data isnt fetching new data please help me
This is my method to fetch data from news org api
Future<List<Article>> getApi() async {
Response response = await get(Uri.parse(
"https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=apikey"));
if (response.statusCode == 200) {
Map<String, dynamic> json = jsonDecode(response.body);
List<dynamic> body = json['articles'];
List<Article> article = body.map((e) => Article.fromJson(e)).toList();
return article;
} else {
throw ("cant get the articles");
}
}
this is my builder to show data
body: FutureBuilder<List<Article>>(
future: futureWords,
builder: (context, AsyncSnapshot<List<Article>> snap) {
if (snap.hasData) {
List<Article> articles = snap.data!;
return RefreshIndicator(
onRefresh: () {
setState(() {});
return _pullRefresh();
},
child: ListView.builder(
itemCount: 20,
itemBuilder: (context, index) {
return customListTile(articles[index]);
}),
);
} else {
return Center(child: CircularProgressIndicator());
}
}),
this is my pullrefresh method
Future<List<Article>> _pullRefresh() async {
List<Article> freshWords = await news.getApi();
setState(() {
futureWords = Future.value(freshWords);
});
return futureWords!;
}

May be it'll help you. If not - post your full code)
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
class Test2 extends StatefulWidget {
const Test2({Key? key}) : super(key: key);
#override
_Test2State createState() => _Test2State();
}
class Article {
String header='';
}
class _Test2State extends State<Test2> {
Future <List<Article>>? futureWords;
#override
void initState() {
super.initState();
_getNews();
}
_getNews() async {
var response = await http.get(Uri.parse(
"https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=aa20aef042a14de5b99a7f7d32952504"));
if (response.statusCode == 200) {
Map<String, dynamic> json = jsonDecode(response.body);
List<dynamic> body = json['articles'];
//List<Article> articles = body.map((e) => Article.fromJson(e)).toList();
List<Article> articles = [];
for (var el in body) {
Article article = Article();
article.header = el['title'];
articles.add(article);
}
articles.shuffle();
setState(() {
futureWords = Future.value(articles);
});
} else {
throw ("cant get the articles. statusCode ${response.statusCode}");
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder<List<Article>>(
future: futureWords,
builder: (context, AsyncSnapshot<List<Article>> snap) {
if (snap.hasData) {
List<Article> articles = snap.data!;
return
RefreshIndicator(
onRefresh: () {
_getNews();
return futureWords!;
},
child: ListView.builder(
itemCount: 10,
itemBuilder: (context, index) {
return ListTile(title: Text(articles[index].header));
}),
);
} else {
return Center(child: CircularProgressIndicator());
}
}),
);
}
}

Related

emit another state when load more data with flutter_bloc

How to implement load more data with flutter_bloc without reload every time: I have this:
post_bloc.dart:
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:scroool/post_events.dart';
import 'package:scroool/post_repo.dart';
import 'package:scroool/post_states.dart';
class PostsBloc extends Bloc<PostEvents, PostsStates> {
PostRepo repo;
int page = 1;
ScrollController controller = ScrollController();
PostsBloc(this.repo) : super(PostInitState()){
on<FetchPosts>((event, emit) async{
emit(PostLoadingState());
final posts = await repo.fetchPosts(page);
emit(PostLoadedState(posts: posts));
});
on<LoadMore>((event, emit) async{
if (controller.position.pixels ==
controller.position.maxScrollExtent) {
emit(LoadMoreState());
page++;
final posts = await repo.fetchPosts(page);
emit(PostLoadedState(posts: posts));
// isLoadingMore = false;
} else {
print("not called");
}
});
}
}
And at home.dart:
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:scroool/post_bloc.dart';
import 'package:scroool/post_events.dart';
import 'package:scroool/post_states.dart';
class Scroool extends StatelessWidget {
List posts = [];
#override
Widget build(BuildContext context) {
return Scaffold(
body: BlocConsumer<PostsBloc, PostsStates>(
listener: (context, state){},
builder: (context, state) {
if(state is PostLoadingState) {
return const Center(child: CircularProgressIndicator(),);
} else if(state is PostLoadedState) {
posts = posts + state.posts;
return ListView.builder(
controller: context.read<PostsBloc>().controller
..addListener(() => context.read<PostsBloc>().add(LoadMore())),
itemCount: state is LoadMoreState
? posts.length + 1 : posts.length ,
itemBuilder: (context, index) {
if(index < posts.length) {
final post = posts[index];
return Card(
child: ListTile(
leading: CircleAvatar(child: Text("${index + 1}"),),
title: Text(post['author'].toString()),
subtitle: Text(post['title']['rendered']),
)
);
} else {
return Center(child: CircularProgressIndicator(),);
}
},
);
} else {
return Container();
}
},
)
);
}
}
It is working without any problem, but every time I need to load more is just re-emit the state and display data from beginning, I need just continue with more data not reload and add all data
Change your BLoC state so the parent state will have property posts. You can set it to empty list for states that do not use it.
abstract class PostState {
final List<Post> posts;
PostState(this.posts);
}
class PostLoadingState extends PostState {
LoadMoreState() : super ([]);
}
class LoadMoreState extends PostState {
LoadMoreState({required List<Post> posts}) : super (posts);
}
class PostLoadedState extends PostState {
PostLoadedState({required List<Post> posts}) : super (posts);
}
Then change your BLoC accordingly:
on<LoadMore>((event, emit) async{
if (controller.position.pixels ==
controller.position.maxScrollExtent) {
emit(LoadMoreState(posts: state.posts));
page++;
final posts = await repo.fetchPosts(page);
emit(PostLoadedState(posts: [...state.posts, ...posts]));
} else {
print("not called");
}
});
In your widget remove the posts variable and use posts from bloc's state. Since your parent state has property posts, you can access posts for every state, including LoadMoreState. So change the if condition to return ListView for all states except PostLoadingState.
class Scroool extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
body: BlocConsumer<PostsBloc, PostsStates>(
listener: (context, state){},
builder: (context, state) {
if(state is PostLoadingState) {
return const Center(child: CircularProgressIndicator(),);
} else {
final posts = state.posts;
return ListView.builder(
controller: context.read<PostsBloc>().controller
..addListener(() => context.read<PostsBloc>().add(LoadMore())),
itemCount: state is LoadMoreState
? posts.length + 1 : posts.length ,
itemBuilder: (context, index) {
if(index < posts.length) {
final post = posts[index];
return Card(
child: ListTile(
leading: CircleAvatar(child: Text("${index + 1}"),),
title: Text(post['author'].toString()),
subtitle: Text(post['title']['rendered']),
)
);
} else {
return Center(child: CircularProgressIndicator(),);
}
},
);
}
},
)
);
}
}

can't see circularprogressindicator while getting data from api in flutter

I am trying to show data from api and while loading data , there should be shown a circularprogressindicator,
but when I start app..it directly showing data instead of circularprogressindicator
class _HomeScreenState extends State<HomeScreen> {
bool isloading = false;
var maplist ;
Future<void> fetchdata() async {
setState(() {
isloading=true;
});
var resp =
await http.get(Uri.parse("https://jsonplaceholder.typicode.com/posts"));
maplist = json.decode(resp.body);
setState(() {
isloading = false;
});
}
#override
void initState() {
// TODO: implement initState
super.initState();
fetchdata();
}
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: MyBody(),
));
}
MyBody() {
return isloading==true ? Center(child: CircularProgressIndicator()) : ListView.builder(
itemCount: maplist.length,
itemBuilder: (context,index){
return Container(
padding: EdgeInsets.all(8.0),
child: Text(maplist[index]['title']));
});
}
}
It's actually working perfectly fine, it shows too fast because it is receiving data quickly(+ could be cache case).
If you like to have more delay you can add, future.delay which is unnecessary
Future<void> fetchdata() async {
setState(() {
isloading = true;
});
var resp =
await http.get(Uri.parse("https://jsonplaceholder.typicode.com/posts"));
maplist = json.decode(resp.body);
// get more delay
await Future.delayed(Duration(seconds: 2));
setState(() {
isloading = false;
});
}
A better of way of handling future method with FutureBuilder
Try the following code:
class _HomeScreenState extends State<HomeScreen> {
var maplist;
Future<void> fetchdata() async {
var resp =
await http.get(Uri.parse("https://jsonplaceholder.typicode.com/posts"));
setState(() {
maplist = json.decode(resp.body);
}
}
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: MyBody(),
));
}
MyBody() {
return FutureBuilder(
future: fetchdata(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const CircularProgressIndicator();
}
return ListView.builder(
itemCount: maplist.length,
itemBuilder: (context,index){
return Container(
padding: EdgeInsets.all(8.0),
child: Text(maplist[index]['title']));
});
}
}
}
You need to use FutureBuilder, it is not good to use async function in initState, try this:
FutureBuilder<List<Map<String,dynamic>>>(
future: fetchdata(),
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
default:
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
List<Map<String,dynamic>> data = snapshot.data ?? [];
return ListView.builder(
itemCount: data.length,
itemBuilder: (context, index) {
return Container(
padding: EdgeInsets.all(8.0),
child: Text(data[index]['title']));
});
}
}
},
),
also you need to change your fetchdata to this:
Future<List<Map<String,dynamic>>> fetchdata() async {
var resp =
await http.get(Uri.parse("https://jsonplaceholder.typicode.com/posts"));
return json.decode(resp.body);
}
Try this one,set isloading default true
class _HomeScreenState extends State<HomeScreen> {
bool isloading = true;
var maplist ;
Future<void> fetchdata() async {
var resp =
await http.get(Uri.parse("https://jsonplaceholder.typicode.com/posts"));
maplist = json.decode(resp.body);
setState(() {
isloading = false;
});
}
#override
void initState() {
// TODO: implement initState
super.initState();
fetchdata();
}
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: MyBody(),
));
}
MyBody() {
return isloading ? Center(child: CircularProgressIndicator()) : ListView.builder(
itemCount: maplist.length,
itemBuilder: (context,index){
return Container(
padding: EdgeInsets.all(8.0),
child: Text(maplist[index]['title']));
});
}
}
You can use like that
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class HomeScreen extends StatefulWidget {
const HomeScreen({super.key});
#override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
bool isloading = false;
var maplist;
Future<void> fetchdata() async {
setState(() {
isloading = true;
});
var resp = await http.get(Uri.parse("https://jsonplaceholder.typicode.com/posts"));
maplist = json.decode(resp.body);
setState(() {
isloading = false;
});
}
#override
void initState() {
super.initState();
fetchdata();
}
#override
Widget build(BuildContext context) {
return SafeArea(
child: isloading ? const CircularProgressIndicator() : const MyBody(),
);
}
}
class MyBody extends StatelessWidget {
const MyBody({super.key});
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
//Write your code here
);
}
}

Flutter #3: I have some async problem in flutter

I have a piece of code to scan and read device information. I have printed the elements in the list in onScan function, however I don't know how to get that information and put it in a listview.
Can someone help me?
List<Data> listDevice = [];
Future<void> getData() async {
var apiEndpoint = TTAPI.shared;
await apiEndpoint.devideScan(((data) => onScan(data)));
}
Future<void> onScan(dynamic data) async {
var dataResponse = DataResponse.fromJson(data);
print(dataResponse.toJson());
List<dynamic> dt = jsonDecode(jsonEncode(dataResponse.data).toString());
dt.forEach((element) {
var item = Data.fromJson(element);
print(item.modelName);
listDevice.add(item);
});
var connectRequest = {
'serialNumber': 'DEVICE_SERIAL',
'modelName': 'DEVICE_MODEL',
'ipAddr': 'DEVICE_IP'
};
var apiEndpoint = TTAPI.shared;
await apiEndpoint.connectDevice(connectRequest);
}
Future<List<Data>> getList() async {
return listDevice;
}
You can see more of my code here: https://docs.google.com/document/d/1ntxaDpyNCLD1MyzJOTmZsrh7-Jfim8cm0Va86IQZGww/edit?usp=sharing
As for the current code structure, listDevice is populated inside Future. So you can call setState to update the UI after getting the list at the end of onScan.
Future<void> getData() async {
var apiEndpoint = TTAPI.shared;
await apiEndpoint.devideScan(((data) => onScan(data)));
setState((){});
}
But it would be great to use FutureBuilder and return list from getData.
Current question pattern example
class TextFW extends StatefulWidget {
const TextFW({super.key});
#override
State<TextFW> createState() => _TextFWState();
}
class _TextFWState extends State<TextFW> {
//for current question way
List<int> listDevice = [];
Future<void> getData() async {
await Future.delayed(Duration(seconds: 2));
/// others async method
listDevice = List.generate(10, (index) => index);
setState(() {}); //here or `getData().then()`
}
#override
void initState() {
super.initState();
getData();
// or this getData().then((value) => setState((){}));
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder(
itemCount: listDevice.length,
itemBuilder: (context, index) => ListTile(
title: Text("${listDevice[index]}"),
),
),
);
}
}
Using FutureBuilder
class TextFW extends StatefulWidget {
const TextFW({super.key});
#override
State<TextFW> createState() => _TextFWState();
}
class _TextFWState extends State<TextFW> {
/// method will provide data by scanning
Future<List<int>> getData() async {
await Future.delayed(Duration(seconds: 2));
return List.generate(10, (index) => index);
}
late final fututre = getData();
#override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder<List<int>>(
future: fututre,
builder: (context, snapshot) {
if (snapshot.hasError) {
return Text("${snapshot.error}");
}
if (snapshot.hasData) {
final listDevice = snapshot.data;
return ListView.builder(
itemCount: listDevice?.length,
itemBuilder: (context, index) => ListTile(
title: Text("${listDevice![index]}"),
),
);
}
return CircularProgressIndicator();
},
),
);
}
}

convert future builder to listview builder

i want to fetch data withour using future, can someone help me to convert it ? direct using listview.builder without using future builder. and how can i post it ? i already try it for a couple days and stuck here. please explain it too
thank you
import 'package:flutter/material.dart';
import 'package:flutter/src/foundation/key.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:latihan_dio/src/features/home/domain/user.dart';
import '../../../../dio_client.dart';
class myHomepage extends StatefulWidget {
const myHomepage({Key? key}) : super(key: key);
#override
State<myHomepage> createState() => _myHomepageState();
}
class _myHomepageState extends State<myHomepage> {
// List<User> users = [];
var selectedIndex = 0;
#override
void initState() {
super.initState();
// fetchData();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: FutureBuilder<List<User>>(
future: fetchData(),
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return Text('Loading....');
default:
// if (snapshot.hasError) {
// return Text('Error: ${snapshot.error}');
// } else {
List<User>? data = snapshot.data;
return ListView.builder(
itemBuilder: (context, index) {
return Column(children: [
Text(data![index].firstName!),
]);
},
itemCount: data?.length,
);
}
}
// },
),
));
}
Future<List<User>> fetchData() async {
var Response = await DioClient().apiCall(
url: 'https://reqres.in/api/users?page=2',
requestType: RequestType.GET,
// queryParameters: {},
);
if (Response.statusCode == 200) {
List<dynamic> listUser = Response.data['data'];
List<User> users = listUser.map((e) => User.fromJson(e)).toList();
return users;
} else {
return [];
}
}
}
// Future<void> fetchData() async {
// var Response = await DioClient().apiCall(
// url: 'https://reqres.in/api/users?page=2',
// requestType: RequestType.GET,
// // queryParameters: {},
// );
// // List<dynamic> listUser = Response.data;
// // OR
// List<dynamic> listUser =
// Response.data['data']; // if you want to access data inside it
// List<User> users = listUser.map((e) => User.fromJson(e)).toList();
// }
as u can see here is my homepage. i make a freeze class and using dio client here.
Try this
class _myHomepageState extends State<myHomepage> {
List<User> user = [];
bool isLoading = false;
#override
void initState() {
initFunction();
super.initState();
}
void initFunction() async {
setState((){
isLoading= true;
})
user = await fetchData();
setState((){
isLoading = false;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: isLoading
? CircularProgressIndicator()
: ListView.builder(
itemBuilder: (context, index) {
return Column(children: [
Text(user[index].firstName!),
]);
},
itemCount: user.length,
);
),
));
}
Future<List<User>> fetchData() async {
var Response = await DioClient().apiCall(
url: 'https://reqres.in/api/users?page=2',
requestType: RequestType.GET,
// queryParameters: {},
);
if (Response.statusCode == 200) {
List<dynamic> listUser = Response.data['data'];
List<User> users = listUser.map((e) => User.fromJson(e)).toList();
return users;
} else {
return [];
}
}
}

'List<dynamic>' is not a subtype of type 'Map<String, dynamic>'

I am trying to fetch a quote from the an api https://type.fit/api/quotes but it's not showing and its show me the this error: type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>'
This is the model class for the json:
class Autogenerated {
String text;
String author;
Autogenerated({this.text, this.author});
factory Autogenerated.fromJson(Map<String, dynamic> json) {
return Autogenerated(
text: json['text'],
author: json['author'],
);
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['text'] = this.text;
data['author'] = this.author;
return data;
}
}
Now this I use the called this import 'package:http/http.dart' as http;
and now I used the http.get to call the api like this:
final response =
await http.get('https://type.fit/api/quotes');
here is the full code of it...
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:quotes_season/modal.dart';
import 'package:http/http.dart' as http;
class Quote extends StatefulWidget {
#override
_QuoteState createState() => _QuoteState();
}
Future<Autogenerated> fetchAlbum() async {
final response =
await http.get('https://type.fit/api/quotes');
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
return Autogenerated.fromJson(json.decode(response.body));
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load album');
}
}
class _QuoteState extends State<Quote> {
Future<Autogenerated> futureAutogenerated;
#override
void initState() {
super.initState();
futureAutogenerated = fetchAlbum();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder(
future: fetchAlbum(),
builder: (context, snapshot) {
if(snapshot.hasData){
return Center(child: Text(snapshot.data.title));
}else if(snapshot.hasError){
return Center(child: Text("${snapshot.error}"));
}
return CircularProgressIndicator();
}),
);
}
}
The site that you posted returns a List of what you modelled in your code as Autogenerated. Based on the rest of your code it seems you only want one of these Autogenerated objects, so you can just say to use the first index in the List that you retrieve.
Future<Autogenerated> fetchAlbum() async {
final response =
await http.get('https://type.fit/api/quotes');
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
List parsedJson = json.decode(response.body);
return parsedJson.isNotEmpty ? Autogenerated.fromJson(parsedJson[0]) : null;
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load album');
}
}
Alternatively, if you want you want to display all of quotes you can parse that and return a list of Autogenerated, but this would involve changing more code in displaying all of the quotes.
Future<List<Autogenerated>> fetchAlbum() async {
final response =
await http.get('https://type.fit/api/quotes');
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
List jsonList = json.decode(response.body);
List list = jsonList.map((elem) => Autogenerated.fromJson(elem)).toList();
return list;
}
...
}
class _QuoteState extends State<Quote> {
Future<List<Autogenerated>> futureAutogenerated;
#override
void initState() {
super.initState();
futureAutogenerated = fetchAlbum();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder(
future: futureAutogenerated,
builder: (context, snapshot) {
if(snapshot.hasData) {
return ListView.builder(itemCount: snapshot.data.length, itemBuilder: (context, index) => Text("${snapshot.data[index].text}, ${snapshot.data[index].author}"));
}else if(snapshot.hasError) {
return Center(child: Text("${snapshot.error}"));
}
return CircularProgressIndicator();
}),
);
}
}
Full Working test code example - this should be used only as a proof of concept, you will need to implement this into your existing code:
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(MaterialApp(home:Quote()));
}
class Quote extends StatefulWidget {
#override
_QuoteState createState() => _QuoteState();
}
Future<List<Autogenerated>> fetchAlbum() async {
final response =
await http.get('https://type.fit/api/quotes');
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
List jsonList = json.decode(response.body);
List list = jsonList.map((elem) => Autogenerated.fromJson(elem)).toList();
return list;
}
else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load album');
}
}
class _QuoteState extends State<Quote> {
Future<List<Autogenerated>> futureAutogenerated;
#override
void initState() {
super.initState();
futureAutogenerated = fetchAlbum();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder(
future: futureAutogenerated,
builder: (context, snapshot) {
if(snapshot.hasData) {
return ListView.builder(itemCount: snapshot.data.length, itemBuilder: (context, index) => Text("${snapshot.data[index].text}, ${snapshot.data[index].author}"));
}else if(snapshot.hasError) {
return Center(child: Text("${snapshot.error}"));
}
return CircularProgressIndicator();
}),
);
}
}
class Autogenerated {
String text;
String author;
Autogenerated({this.text, this.author});
factory Autogenerated.fromJson(Map<String, dynamic> json) {
return Autogenerated(
text: json['text'],
author: json['author'],
);
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['text'] = this.text;
data['author'] = this.author;
return data;
}
}
You are trying to fetch JSON list from the API endpoint, but your parsing code is parsing single JSON object.
Your method has to change to return list of objects:
Future<List<Autogenerated>> fetchAlbum() async {
final response =
await http.get('https://type.fit/api/quotes');
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
List jsonList = json.decode(response.body)
List list = List.generate(jsonList.length, (i) => Autogenerated.fromJson(jsonList[i]));
return list;
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load album');
}
}
After this change of the API call, your state class should look like this:
class _QuoteState extends State<Quote> {
Future<List<Autogenerated>> futureAutogenerated;
#override
void initState() {
super.initState();
futureAutogenerated = fetchAlbum();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder(
future: futureAutogenerated,
builder: (context, snapshot) {
if(snapshot.hasData){
List<Autogenerated> list = snapshot.data;
Autogenerated firstItem = list[0];
return Center(child: Text(firstItem.text));
}else if(snapshot.hasError){
return Center(child: Text("${snapshot.error}"));
}
return CircularProgressIndicator();
}),
);
}
}
If your goal is to create a list of elements, and not a single element, you would need to modify widget being used:
return Center(child: Text(firstItem.text));
and do something like this instead:
List<Autogenerated> list = snapshot.data;
return ListView.builder(
itemCount: list.length,
itemBuilder: (context, index) => Text(list[index]),
);