Skip to content

Instantly share code, notes, and snippets.

@ctechdev
Forked from branflake2267/main.dart
Created August 5, 2021 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ctechdev/1a7e0ff1a31ed097cbd1d591c5ca7b09 to your computer and use it in GitHub Desktop.
Save ctechdev/1a7e0ff1a31ed097cbd1d591c5ca7b09 to your computer and use it in GitHub Desktop.
Flutter - Using the future builder with infinite list view.
import 'dart:async';
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
var futureBuilder = new FutureBuilder(
future: _getData(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
case ConnectionState.waiting:
return new Text('loading...');
default:
if (snapshot.hasError)
return new Text('Error: ${snapshot.error}');
else
return createListView(context, snapshot);
}
},
);
return new Scaffold(
appBar: new AppBar(
title: new Text("Home Page"),
),
body: futureBuilder,
);
}
Future<List<String>> _getData() async {
var values = new List<String>();
values.add("Horses");
values.add("Goats");
values.add("Chickens");
//throw new Exception("Danger Will Robinson!!!");
await new Future.delayed(new Duration(seconds: 5));
return values;
}
Widget createListView(BuildContext context, AsyncSnapshot snapshot) {
List<String> values = snapshot.data;
return new ListView.builder(
itemCount: values.length,
itemBuilder: (BuildContext context, int index) {
return new Column(
children: <Widget>[
new ListTile(
title: new Text(values[index]),
),
new Divider(height: 2.0,),
],
);
},
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment