1

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]),
        );
      },
    );
  }
}

1 Answer 1

2

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

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

  setState(() {
      _counter++;
    });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.