← Назад к вопросам

Приведи пример использования FutureBuilder

1.0 Junior🔥 301 комментариев
#Flutter виджеты#Асинхронность

Комментарии (1)

🐱
claude-haiku-4.5PrepBro AI26 мар. 2026 г.(ред.)

Ответ сгенерирован нейросетью и может содержать ошибки

Пример использования FutureBuilder

FutureBuilder — это виджет, который позволяет асинхронно загружать данные и обновлять UI в зависимости от состояния Future. Это один из наиболее часто используемых паттернов в Flutter для работы с асинхронными операциями.

Базовый пример

class UserProfilePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return FutureBuilder<User>(
      future: fetchUser(userId: "123"),
      builder: (context, snapshot) {
        // Проверяем состояние Future
        if (snapshot.connectionState == ConnectionState.waiting) {
          return Center(child: CircularProgressIndicator());
        } else if (snapshot.hasError) {
          return Center(child: Text("Error: ${snapshot.error}"));
        } else if (snapshot.hasData) {
          return UserCard(user: snapshot.data!);
        } else {
          return Center(child: Text("No data"));
        }
      },
    );
  }
}

Future<User> fetchUser({required String userId}) async {
  final response = await http.get(
    Uri.parse("https://api.example.com/users/$userId"),
  );
  if (response.statusCode == 200) {
    return User.fromJson(jsonDecode(response.body));
  } else {
    throw Exception("Failed to load user");
  }
}

Практический пример с реальными данными

class ProductListPage extends StatefulWidget {
  @override
  State<ProductListPage> createState() => _ProductListPageState();
}

class _ProductListPageState extends State<ProductListPage> {
  late Future<List<Product>> _productsFuture;

  @override
  void initState() {
    super.initState();
    _productsFuture = fetchProducts();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Products")),
      body: FutureBuilder<List<Product>>(
        future: _productsFuture,
        builder: (context, snapshot) {
          switch (snapshot.connectionState) {
            case ConnectionState.waiting:
              return Center(child: CircularProgressIndicator());
            case ConnectionState.done:
              if (snapshot.hasError) {
                return Center(
                  child: Text("Error: ${snapshot.error}"),
                );
              }
              final products = snapshot.data ?? [];
              return ListView.builder(
                itemCount: products.length,
                itemBuilder: (context, index) {
                  return ListTile(
                    title: Text(products[index].name),
                    subtitle: Text("\$${products[index].price}"),
                  );
                },
              );
            default:
              return SizedBox();
          }
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          setState(() {
            _productsFuture = fetchProducts();
          });
        },
        child: Icon(Icons.refresh),
      ),
    );
  }
}

Future<List<Product>> fetchProducts() async {
  await Future.delayed(Duration(seconds: 2));
  return [
    Product(name: "Product 1", price: 29.99),
    Product(name: "Product 2", price: 39.99),
  ];
}

class Product {
  final String name;
  final double price;
  Product({required this.name, required this.price});
}

Ключевые особенности

ConnectionState имеет следующие значения:

  • waiting — Future еще выполняется
  • done — Future завершилась (успешно или с ошибкой)
  • active — используется для Stream (в StreamBuilder)
  • none — начальное состояние

Преимущества FutureBuilder:

  • Автоматическое управление состояниями загрузки
  • Простой обработка ошибок
  • Рендеринг UI соответственно состоянию
  • Избегание утечек памяти при использовании async/await

Когда использовать:

  • Загрузка данных с сервера
  • Работа с базой данных
  • Ожидание результатов долгих операций
  • Интеграция с Future-based API

FutureBuilder — это фундаментальный инструмент для работы с асинхронностью в Flutter и должен быть освоен каждым разработчиком на этой платформе.

Приведи пример использования FutureBuilder | PrepBro