日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Flutter如何輕松實現動態更新ListView淺析_Android

作者:技術小黑屋 ? 更新時間: 2022-04-20 編程語言

前言

在 App 開發過程中,ListView 是 比較很常見的控件,用來處理 列表類的數據展示。當然 Flutter 也是支持的,由于 Flutter 是歸屬于聲明式 UI 編程,其處理起來要更加的簡單與便捷。

本文將通過一個極簡單的例子來說明一下 如何 實現動態更新數據。 在貼代碼之前,先介紹一些概念和內容

數據集

final _names = ['Andrew', 'Bob', 'Charles'];
int _counter = 0;

新的數據Item?'Someone($_counter)'?會被觸發加入到 _names 數組中。

觸發器

通常觸發加載數據是分頁數據加載完成,這里我們使用一個?FloatingActionButton?的點擊操作等價模擬。

floatingActionButton: FloatingActionButton(
 onPressed: () {
   setState(() {
     _names.add('Someone($_counter)');
     _counter ++;
   });
 },
 tooltip: 'Add TimeStamp',
 child: const Icon(Icons.add),

展示視圖

Expanded(
 child: ListView.builder(
     itemCount: _names.length,
     itemBuilder: (BuildContext context, int index) {
       return Container(
           width: double.infinity,
           height: 50,
           alignment: Alignment.center,
           child: Text(_names[index]));
     }),
),

上述代碼

需要Expanded 包裹 ListView 確保空間展示填充 使用 ListView.builder 方法實現 ListView

總體來說,Flutter 中實現 ListView 數據動態添加和展示,真的很便捷,少去了傳統UI 編程中顯式的 Adapter 等內容,編碼效率提升不少。

完整代碼

import 'package:flutter/material.dart';

void main() {
 runApp(const MyApp());
}

class MyApp extends StatelessWidget {
 const MyApp({Key? key}) : super(key: key);

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

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

 final String title;

 @override
 State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
 final _names = ['Andrew', 'Bob', 'Charles'];
 int _counter = 0;

 @override
 Widget build(BuildContext context) {

   return Scaffold(
     appBar: AppBar(
       title: Text(widget.title),
     ),
     body: Column(
       children: [
         Expanded(
           child: ListView.builder(
               itemCount: _names.length,
               itemBuilder: (BuildContext context, int index) {
                 return Container(
                     width: double.infinity,
                     height: 50,
                     alignment: Alignment.center,
                     child: Text(_names[index]));
               }),
         ),
       ],

     ),
     floatingActionButton: FloatingActionButton(
       onPressed: () {
         setState(() {
           _names.add('Someone($_counter)');
           _counter ++;
         });
       },
       tooltip: 'Add TimeStamp',
       child: const Icon(Icons.add),
     ), // This trailing comma makes auto-formatting nicer for build methods.
   );
 }
}

以上。

總結

原文鏈接:https://droidyue.com/blog/2022/02/13/flutter-update-listview-dynamically/

欄目分類
最近更新