【问题标题】:Async Listview update in flutterFlutter 中的异步 Listview 更新
【发布时间】:2019-11-30 02:40:06
【问题描述】:

我创建了一个程序,它在 build 方法中显示列表视图,在 init 中我有一个 async 方法。 3 秒后的异步方法在列表中添加一个元素并尝试设置状态。

它不工作。我的代码如下。 在 init 中调用异步函数可能是错误的,我想显示列表视图然后进行异步 http 调用,然后更新列表视图。即使在推送和弹出之后,这也应该可以工作。

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

【问题讨论】:

    标签: flutter


    【解决方案1】:

    使用超时方法句柄并在该方法中调用setState方法,如下所示

     Timer(ThreeSec, () {
      europeanCountries.insert(0, "Testing");
      print(europeanCountries);
    
      setState(() {
          _counter++;
        });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-29
      • 2015-11-24
      • 2017-04-12
      • 1970-01-01
      • 2018-01-20
      • 2021-01-10
      • 2022-01-05
      相关资源
      最近更新 更多