最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

if more than one api call on flutter and some complex design then it wil be take time? - Stack Overflow

programmeradmin2浏览0评论

I am trying to increase app speed of some complex and icon based design in my flutter application. We call 4 api's in initState, because its necessary. So application taking time using async and await also.

How can we make this faster?

I am trying to increase app speed of some complex and icon based design in my flutter application. We call 4 api's in initState, because its necessary. So application taking time using async and await also.

How can we make this faster?

Share Improve this question edited Nov 21, 2024 at 14:17 Frank van Puffelen 600k85 gold badges889 silver badges859 bronze badges asked Nov 21, 2024 at 5:25 Inam ur RahmanInam ur Rahman 334 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 1

The speed of API calls depends on several factors,

  1. Server Performance: Response time, database optimization, and load handling.
  2. Network Latency: Internet speed and server location.
  3. Payload Size: Smaller payloads are faster.
  4. Concurrency: Parallel calls are faster for independent APIs.

Optimization Tips

  1. Use Future.wait for parallel calls.
  2. Fetch only necessary data (e.g., pagination, filtering).

To measure the speed you can do like this:

void measureApiSpeed() async {
  final start = DateTime.now();
  await fetchApi(); // Replace with your API call
  print('Time taken: ${DateTime.now().difference(start).inMilliseconds}ms');
}

For parellel API calls use Future.wait

class OrdersPage extends StatelessWidget {
  const OrdersPage({super.key});

  Future<String> fetchUserData() async {
    await Future.delayed(const Duration(seconds: 2)); // Simulate API delay
    return 'User Data';
  }

  Future<String> fetchOrderDetails() async {
    await Future.delayed(const Duration(seconds: 3)); // Simulate API delay
    return 'Order Details';
  }

  Future<String> fetchNotifications() async {
    await Future.delayed(const Duration(seconds: 1)); // Simulate API delay
    return 'Notifications';
  }

  Future<List<String>> fetchAllData() async {
    try {
      // Start all API calls concurrently
      final results = await Future.wait([
        fetchUserData(),
        fetchOrderDetails(),
        fetchNotifications(),
      ]);

      return results;
    } catch (error) {
      throw 'Error fetching data: $error';
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: FutureBuilder(
          future: fetchAllData(),
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              final data = snapshot.data as List<String>;
              return Column(
                children: [
                  Text(data[0]),
                  Text(data[1]),
                  Text(data[2]),
                ],
              );
            } else if (snapshot.hasError) {
              return Center(child: Text(snapshot.error.toString()));
            } else {
              return const Center(child: CircularProgressIndicator());
            }
          }),
    );
  }
}

To speed up your app you can follow below steps:

Combine API Requests:

Discuss with your backend developer to merge the APIs into a single request that returns all the required data in one response, or reduce it from 4 to 2 or something like that. For example, if one API fetches homepage details and another fetches user details, pass user-specific parameters in a single request and get everything at once.

Optimize Frontend Loading:

If combining APIs isn't possible, prioritize loading essential data first. Use shimmer placeholders or similar for sections dependent on secondary APIs. Fetch secondory prioritized data in background using asynchronous updates (e.g., StreamBuilder or FutureBuilder).

Caching:

Cache static or semi-static data to reduce repeated API calls.

UI Optimization:

Simplify widget trees for complex designs and avoid unnecessary rebuilds

发布评论

评论列表(0)

  1. 暂无评论