max
max

Reputation: 1675

Async Listview update in flutter

I have created a program which displays a list view in build method and in init I have a async method. That async method after 3 seconds adds an element in list and try to set State.

It is not working. My code is as follows. calling async function in init may be wrong, i want to show the List view then make an async http call and then update the list view. and this should work even after push and pop.

import 'dart:async';

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<String> europeanCountries = [
    'Albania',
    'Andorra',
    'Armenia',
    'Austria',
    'Azerbaijan',
    'Belarus',
    'Belgium',
    'Bosnia and Herzegovina'
  ];
  int _counter = 0;

  void _incrementCounter() async {
    const ThreeSec = const Duration(seconds: 3);
    Timer(ThreeSec, () {
      europeanCountries.insert(0, "Testing");
      print(europeanCountries);
    });

    setState(() {
      _counter++;
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _incrementCounter();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: _myListView(context),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }

  Widget _myListView(BuildContext context) {
    // backing data

    return ListView.builder(
      itemCount: europeanCountries.length,
      reverse: true,
      itemBuilder: (context, index) {
        return ListTile(
          title: Text(europeanCountries[index]),
        );
      },
    );
  }
}

Upvotes: 1

Views: 896

Answers (1)

Krunal Dave
Krunal Dave

Reputation: 113

Use timeout method handle and call setState method inside that method like following way

 Timer(ThreeSec, () {
  europeanCountries.insert(0, "Testing");
  print(europeanCountries);

  setState(() {
      _counter++;
    });
});

Upvotes: 2

Related Questions