lang/dart

Flutter - FutureBuilder

C/H 2020. 9. 22. 08:30

Flutter - FutureBuilder

main.dart

import 'package:flutter/material.dart';
import 'src/app.dart';

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

src/app.dart

import 'package:flutter/material.dart';
import 'screens/news_list.dart';

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'HackerNews',
      home: NewsList(),
    );
  }
}

src/screens/news_list.dart

import 'package:flutter/material.dart';

class NewsList extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Top News'),
      ),
      body: buildList(),
    );
  }

  Widget buildList() {
    return ListView.builder(
      itemCount: 1000,
      itemBuilder: (context, index) {
        return FutureBuilder(
          future: getFuture(),
          builder: (context, snapshot) {
            return Container(
              height: 80,
              child: snapshot.hasData
                  ? Text(
                      'Im visible $index',
                      style: TextStyle(color: Colors.blue),
                    )
                  : Text(
                      'I havent fetched yet $index',
                      style: TextStyle(color: Colors.red),
                    ),
            );
          },
        );
      },
    );
  }

  getFuture() {
    return Future.delayed(
      Duration(seconds: 1),
      () => 'hi',
    );
  }
}

Item Visible
fetchIem timeline
Future pending

 

 

반응형